﻿using ManageLiteAV;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PhilipService.Entity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using TCommon;
using TCommon.Entity;
using TCommon.Enum;
using TCommon.Util;
using TRTCCSharpDemo;
using TRTCCSharpDemo.Common;
using TRTCMain;
using TRTCMain.Common;
using TRTCMain.Controls;
using TRTCMain.Properties;
using VirtualCamera;

namespace TRTC
{
    public partial class VideoMainForm : Form, ITRTCCloudCallback, ITRTCLogCallback
    {
        private int roomId;
        private string name;
        private Window loginWindow1;
        private UserRole role;
        private string UserSign;
        private int Time = 0;
        public int Count = 0;//最大方数
        private DateTime startTime;
        private string HostId;
        private bool ShowClosePrompt = true;

        private bool meetingLoaded = false;

        private int videoContainerWidth = 0;
        private int videoContainerHeight = 0;
        private int formWidth = 0;
        private int formHeight = 0;
        private FormWindowState fromState;

        System.Threading.Timer threadTimer;

        //标志主持人是否已完成进入房间
        bool enterRoom = false;

        private int mainThreadId;

        private string mUserId;
        private uint mRoomId;
        private ITRTCCloud mTRTCCloud;

        private bool isPhilipMode = false;

        // 记录大小界面显示的是摄像头还是屏幕
        private IntPtr mCameraLocalVideo;
        private IntPtr mScreenLocalVideo;

        private List<UserVideoMeta> mMixStreamVideoMeta;
        private bool mIsEnterSuccess;    // 是否进房成功
        private bool mIsSetScreenSuccess;   // 是否设置屏幕参数成功

        private List<string> mRoomUsers;    // 当前房间里的远端用户（除了本地用户）
        private static List<string> userOnRequest = new List<string>(); 

        private string mCurCameraDevice;
        private string mCurMicDevice;
        private string mCurSpeakerDevice;

        private TRTCDeviceForm mDeviceForm;
        private TRTCSettingForm mSettingForm;
        private StopSharingDesktopForm mStopSharingDesktopForm;

        private AppRecordForm recordForm;
        private DeviceDetailForm deviceForm;
        private VolumeControl volumeControl = null;
        private DateTime speakTime = DateTime.Now;
        private int mLogLevel = 0;

        public bool islive1 = false;
        public static string isscene1 = "";
        private bool cachMicroBtnStatus = true;
        public static bool topupmai = false;
        private delegate void SetNetEnvDelegate(int bTestEnv);
        private TRTCRoleType currentRole;

        #region Philips
        public delegate void NoteChangeHandler(long serviceId, string note);
        public event NoteChangeHandler NoteChanged;
        private long ServiceId = -1;
        private GetDeviceInfoResponse deviceInfo;

        public delegate void RemoveUserHandler(string userId, long serviceId);
        public event RemoveUserHandler RemoveUserClicked;
        #endregion

        [DllImport("liteav.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern void setNetEnv(int bTestEnv);
        public void EnterRoom(TRTCParams @params)
        {
            // 初始化“停止共享”按钮
            //mTRTCCloud.enableAudioVolumeEvaluation(300);
            mStopSharingDesktopForm = new StopSharingDesktopForm();
            mStopSharingDesktopForm.BtnClicked += () =>
            {
                shareButton.IsChecked = false;
                this.WindowState = FormWindowState.Normal;
            };

            userList.SetCloud(mTRTCCloud);
            try
            {
                if (isscene1 == "1")
                {
                    //microButton.Enabled = false;
                    //cameraButton.Enabled = false;
                    //shareButton.Enabled = false;
                    //layoutButton1.Enabled = false;
                    //handButton.Enabled = false;
                    //dwonAllHandButton.Enabled = false;
                    //livesButton1.Enabled = false;
                    //stopShareButton.Enabled = false;
                    //muteAllButton.Enabled = false;
                }
                else
                {
                    mCameraLocalVideo = videoContainer.GetVideoHandle(this.name);
                    userList.AddUser(this.name);
                }
                //MessageReceived();
                videoContainer.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
                //mScreenLocalVideo = videoContainer.GetShareHandle(this.name);
                // 大画面的编码器参数设置
                // 设置视频编码参数，包括分辨率、帧率、码率等等，这些编码参数来自于 TRTCSettingViewController 的设置
                // 注意（1）：不要在码率很低的情况下设置很高的分辨率，会出现较大的马赛克
                // 注意（2）：不要设置超过25FPS以上的帧率，因为电影才使用24FPS，我们一般推荐15FPS，这样能将更多的码率分配给画质
                TRTCVideoEncParam encParams = PropertySaver.GetInstance().encParams;
                TRTCNetworkQosParam qosParams = PropertySaver.GetInstance().qosParams;
                mTRTCCloud.setVideoEncoderParam(ref encParams);
                mTRTCCloud.setNetworkQosParam(ref qosParams);

                bool pushSmallVideo = PropertySaver.GetInstance().pushSmallVideo;
                bool playSmallVideo = PropertySaver.GetInstance().playSmallVideo;

                if (pushSmallVideo)
                {
                    //小画面的编码器参数设置
                    //TRTC SDK 支持大小两路画面的同时编码和传输，这样网速不理想的用户可以选择观看小画面
                    //注意：iPhone & Android 不要开启大小双路画面，非常浪费流量，大小路画面适合 Windows 和 MAC 这样的有线网络环境
                    TRTCVideoEncParam param = new TRTCVideoEncParam
                    {
                        videoFps = 15,
                        videoBitrate = 100,
                        videoResolution = TRTCVideoResolution.TRTCVideoResolution_320_240
                    };
                    mTRTCCloud.enableSmallVideoStream(pushSmallVideo, ref param);
                }
                if (playSmallVideo)
                {
                    mTRTCCloud.setPriorRemoteVideoStreamType(TRTCVideoStreamType.TRTCVideoStreamTypeSmall);
                }

                mTRTCCloud.enterRoom(ref @params, PropertySaver.GetInstance().appScene);
                mUserId = @params.userId;
                mRoomId = @params.roomId;
                //this.roomLabel.Text = "房间号：" + @params.roomId.ToString() + "   用户名：" + @params.userId;
                //this.localUserLabel.Text = mUserId;

                mTRTCCloud.setLocalViewFillMode(TRTCVideoFillMode.TRTCVideoFillMode_Fit);
                if (TCommon.AppContext.startFromOldVersion)
                {
                    if (IsMainThread())
                    {
                        microButton.Visible = false;
                        arrowAudioButton.Visible = false;
                        shareButton.Visible = false;
                        layoutButton1.Visible = false;
                        chatButton1.Visible = false;
                        stopShareButton.Visible = false;
                        muteAllButton.Visible = false;
                        livesButton1.Visible = false;
                        cameraButton.Location = new System.Drawing.Point(1, -2);
                        arrowVideoButton.Location = new System.Drawing.Point(78, 1);
                        settingButton.Location = new System.Drawing.Point(105, -1);
                        usersButton.Location = new System.Drawing.Point(170, 1);
                        if (!TCommon.AppContext.isHost)
                        {
                            cameraButton.Visible = false;
                            arrowVideoButton.Visible = false;
                            settingButton.Visible = false;
                            usersButton.Location = new System.Drawing.Point(1, 1);
                        }
                    }
                    else
                    {
                        this.BeginInvoke(new System.Action(() =>
                        {
                            microButton.Visible = false;
                            arrowAudioButton.Visible = false;
                            shareButton.Visible = false;
                            layoutButton1.Visible = false;
                            chatButton1.Visible = false;
                            stopShareButton.Visible = false;
                            muteAllButton.Visible = false;
                            livesButton1.Visible = false;
                            cameraButton.Location = new System.Drawing.Point(1, -2);
                            arrowVideoButton.Location = new System.Drawing.Point(78, 1);
                            settingButton.Location = new System.Drawing.Point(105, -1);
                            usersButton.Location = new System.Drawing.Point(170, 1);
                            if (!TCommon.AppContext.isHost)
                            {
                                cameraButton.Visible = false;
                                arrowVideoButton.Visible = false;
                                settingButton.Visible = false;
                                usersButton.Location = new System.Drawing.Point(1, 1);
                            }
                        }));
                    }
                    if (!TCommon.AppContext.isHost)
                    {
                        string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":10,\"userid\":\"{2}\"{3}", "{", TRTC.VideoMainForm.roomId1, name, "}");
                        fasongmessage(inputMsg);
                        if (IsMainThread())
                        {
                            cameraButton.Visible = false;
                            arrowVideoButton.Visible = false;
                            settingButton.Visible = false;
                            upanddownwheat1.Visible = false;
                            handButton.Visible = false;
                            usersButton.Location = new System.Drawing.Point(1, 1);
                        }
                        else
                        {
                            this.BeginInvoke(new System.Action(() =>
                            {                             
                                cameraButton.Visible = false;
                                arrowVideoButton.Visible = false;
                                settingButton.Visible = false;
                                upanddownwheat1.Visible = false;
                                handButton.Visible = false;
                                usersButton.Location = new System.Drawing.Point(1, 1);
                            }));
                        }
                    }
                    else
                    {
                        mTRTCCloud.startLocalPreview(mCameraLocalVideo);
                        InitDevice();
                        //默认禁止聊天
                        string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2}{3}", "{", TRTC.VideoMainForm.roomId1, 127, "}");
                        TRTC.VideoMainForm.fasongmessage(inputMsg);
                        //默认禁止上麦
                        inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2}{3}", "{", TRTC.VideoMainForm.roomId1, 129, "}");
                        TRTC.VideoMainForm.fasongmessage(inputMsg);

                        TCommon.AppContext.AllowChat = false;
                        TCommon.AppContext.AllowOnMic = false;
                    }
                }
                else if (isscene1 == "1")
                {

                    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":10,\"userid\":\"{2}\"{3}", "{", TRTC.VideoMainForm.roomId1, name, "}");
                    fasongmessage(inputMsg);
                    //  mTRTCCloud.stopLocalPreview();
                    //mTRTCCloud.startLocalAudio();
                    // mTRTCCloud.startLocalAudio();
                    InitDevice();
                }
                else
                {
                    mTRTCCloud.startLocalPreview(mCameraLocalVideo);


                    mTRTCCloud.startLocalAudio();
                    // mTRTCCloud.startLocalAudio();
                    InitDevice();
                    userList.SetCloud(mTRTCCloud);
                    if (IsMainThread())
                    {
                        userList.UpdateVideoStatus(this.name, true);
                        userList.UpdateAudioStatus(this.name, true);
                    }
                    else
                        this.BeginInvoke(new System.Action(() =>
                        {
                            userList.UpdateVideoStatus(this.name, true);
                            userList.UpdateAudioStatus(this.name, true);
                        }));
                }
                //Task.Factory.StartNew(new Action(() =>
                //{
                //    for (int i = 0; i < 2; i++)
                //    {
                //        Thread.Sleep(200);
                //        this.Invoke(new Action(() =>
                //        {
                //            GetHandleAndSetUserId(StringUtil.ToHex(i.ToString()), false);
                //            userList.AddUser(StringUtil.ToHex(i.ToString()));
                //        }));
                //    }

                //    //    //Thread.Sleep(5000);
                //    //    //this.Invoke(new Action(() =>
                //    //    //{
                //    //    //    videoContainer.RemoveUser("0");
                //    //    //}));
                //    //    //Thread.Sleep(2000);
                //    //    //this.Invoke(new Action(() =>
                //    //    //{
                //    //    //    videoContainer.RemoveUser("2");
                //}));
            }
            catch (Exception ex)
            {

                System.Windows.MessageBox.Show(ex.ToString());
            }
        }

        private void InitDevice()
        {
            ITRTCDeviceCollection cameraList = mTRTCCloud.getCameraDevicesList();
            if (cameraList.getCount() <= 0)
                ShowMessage("Error: 未检出到摄像头，请检查本地电脑设备。");
            else
            {
                ITRTCDeviceInfo camera = mTRTCCloud.getCurrentCameraDevice();
                mCurCameraDevice = camera.getDeviceName();

                if (!string.IsNullOrEmpty(MeetingConfig.GetInstance().CameraName))
                {
                    for (uint i = 0; i < cameraList.getCount(); i++)
                    {
                        if (MeetingConfig.GetInstance().CameraName == AppConst.VirtualCameraName)
                        {
                            if (cameraList.getDeviceName(i) != AppConst.VirtualCameraName)
                            {
                                mTRTCCloud.setCurrentCameraDevice(cameraList.getDevicePID(i));
                                mCurCameraDevice = cameraList.getDeviceName(i);
                                break;
                            }
                        }
                        else
                        {
                            if (cameraList.getDeviceName(i) == MeetingConfig.GetInstance().CameraName)
                            {
                                mTRTCCloud.setCurrentCameraDevice(cameraList.getDevicePID(i));
                                mCurCameraDevice = cameraList.getDeviceName(i);
                                break;
                            }
                        }
                    }
                }
                //else if (mCurCameraDevice == AppConst.VirtualCameraName 
                //    && !TCommon.AppContext.startFromOldVersion) {
                //    for (uint i = 0; i < cameraList.getCount(); i++) {
                //        if (cameraList.getDeviceName(i) != AppConst.VirtualCameraName) {
                //            mTRTCCloud.setCurrentCameraDevice(cameraList.getDevicePID(i));
                //            mCurCameraDevice = cameraList.getDeviceName(i);
                //            break;
                //        }
                //    }
                //}

                //if (mCurCameraDevice == AppConst.VirtualCameraName) {
                //    if (mSettingForm == null)
                //    {
                //        mSettingForm = new TRTCSettingForm(mTRTCCloud, this);
                //    }
                //    mSettingForm.SetCameraHighResolution();
                //    TCommon.AppContext.VirtualCamera.StartCaptureScreen();
                //    mTRTCCloud.startSystemAudioLoopback("");
                //    mTRTCCloud.setSystemAudioLoopbackVolume(80);
                //}
            }
            cameraList.release();

            ITRTCDeviceCollection micList = mTRTCCloud.getMicDevicesList();
            if (micList.getCount() <= 0)
                ShowMessage("Error: 未检出到麦克风，请检查本地电脑设备。");
            else
            {
                if (!string.IsNullOrEmpty(MeetingConfig.GetInstance().MicroName)) {
                    for (uint i = 0; i < micList.getCount(); i++)
                    {
                        if (micList.getDeviceName(i) == MeetingConfig.GetInstance().MicroName)
                        {
                            mTRTCCloud.setCurrentMicDevice(micList.getDevicePID(i));
                            mCurMicDevice = micList.getDeviceName(i);
                            mTRTCCloud.setCurrentMicDeviceVolume((uint)(MeetingConfig.GetInstance().MicroVolume*100/100));
                            break;
                        }
                    }
                }
            }
            micList.release();
            ITRTCDeviceCollection speakerList = mTRTCCloud.getSpeakerDevicesList();
            if (speakerList.getCount() <= 0)
                ShowMessage("Error: 未检出到扬声器，请检查本地电脑设备。");
            else
            {
                if (!string.IsNullOrEmpty(MeetingConfig.GetInstance().SpeakerName))
                {
                    for (uint i = 0; i < speakerList.getCount(); i++)
                    {
                        if (speakerList.getDeviceName(i) == MeetingConfig.GetInstance().SpeakerName)
                        {
                            mTRTCCloud.setCurrentSpeakerDevice (speakerList.getDevicePID(i));
                            mCurSpeakerDevice = speakerList.getDeviceName(i);
                            mTRTCCloud.setCurrentSpeakerVolume((uint)(MeetingConfig.GetInstance().SpeakerVolume * 100 / 100));
                            break;
                        }
                    }
                }
            }
            speakerList.release();
        }

        private void ShowMessage(string text, int delay = 0)
        {
            this.BeginInvoke(new System.Action(() =>
            {
                MessageForm msgBox = new MessageForm();
                msgBox.setText(text, delay);
                msgBox.setCancelBtn(false);
                msgBox.ShowDialog();
            }));
        }

        public void onLog(string log, TRTCLogLevel level, string module)
        {
            //throw new NotImplementedException();
        }

        public void onError(TXLiteAVError errCode, string errMsg, IntPtr arg)
        {
            if (errCode == TXLiteAVError.ERR_ROOM_ENTER_FAIL)
            {
                System.Windows.Forms.MessageBox.Show(String.Format("errCode : {0}, errMsg : {1}, arg = {2}", errCode, errMsg, arg));
                //Log.E(String.Format("errCode : {0}, errMsg : {1}, arg = {2}", errCode, errMsg, arg));
                // 检查userSig是否合法、网络是否正常等
            }
        }

        public void onWarning(TXLiteAVWarning warningCode, string warningMsg, IntPtr arg)
        {
            //throw new NotImplementedException();
        }
        public void onEnterRoom(int result)
        {
            UpdateMixTranCodeInfo();
            if (result >= 0)
            {
                mIsEnterSuccess = true;
                //Log.I(String.Format("network timeout = {0}", result));
                if (role == UserRole.Host)
                {
                    Task.Factory.StartNew(new Action(() =>
                    {
                        if (islive1 == true)
                        {
                            HostMeetingLive(this.roomId);
                        }
                        else
                        {
                            if (!isPhilipMode)
                            {
                                HostMeeting(this.roomId);
                            }

                        }

                    }));
                }
            }
            else
            {
                mIsEnterSuccess = false;
                ShowMessage("进房失败，请重试");
                //Log.E(String.Format("onEnterRoom : enterRoom failed."));
            }

            threadTimer = new System.Threading.Timer(new TimerCallback(TimerUp), null, 1000, 10000);
            try
            {


                if (this.role == UserRole.Host)
                {
                    if (IsMainThread())
                        userList.SetHostUser(this.name);
                    else
                        this.BeginInvoke(new System.Action(() =>
                        {
                            userList.SetHostUser(this.name);
                        }));
                }
            }
            catch (Exception ex)
            {

                System.Windows.MessageBox.Show(ex.ToString());
            }

            Task.Factory.StartNew(new Action(() =>
            {
                Thread.Sleep(2000);
                var manager = new ServiceManager();
                string roomId = string.Empty;
                var focusedUser = manager.GetFocuseUser(TCommon.AppContext.AttendRoomId);
                if (!string.IsNullOrEmpty(focusedUser))
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        videoContainer.SetFocuseUser(focusedUser);
                        userList.SetFocuseUser(focusedUser);
                        Focuse = focusedUser;
                    }));
                }
            }));
        }
        bool isdatetime = true;
        private void TimerUp(object param)
        {

            try
            {
                if (!this.enterRoom)
                {
                    try
                    {
                        this.BeginInvoke(new System.Action(() =>
                        {
                            if (!this.enterRoom)
                            {
                                userList.SetHostUser(this.HostId);
                                this.enterRoom = true;
                            }
                        }));
                    }
                    catch (Exception ex)
                    {

                        System.Windows.MessageBox.Show(ex.ToString());
                    }
                }

                if (Time == 0)
                    return;

                if (isdatetime == true && (DateTime.Now - startTime).TotalSeconds >= Time - 60*10)
                {
                    isdatetime = false;
                    System.Windows.MessageBox.Show("离本次会议结束还剩10分钟");
                    return;
                }

                if ((DateTime.Now - startTime).TotalSeconds >= Time)
                {
                    try
                    {
                        threadTimer.Change(-1, -1);
                        var action = new ActionEntity()
                        {
                            ActionId = HostAction.MeetingTimeout,
                        };
                        var jsonString = JsonConvert.SerializeObject(action);
                        var data = Encoding.UTF8.GetBytes(jsonString);
                        mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);

                        Uninit(true);
                        this.BeginInvoke(new System.Action(() => 
                        {
                            videoContainer.clearNormalScreenUsers();
                            userList.clearNormalScreenUsers();
                            ShowClosePrompt = false;
                            this.Close();
                            this.loginWindow11?.Show();
                            System.Windows.MessageBox.Show("会议时间已用完,会议自动结束");
                        }));
                        threadTimer.Dispose();
                    }
                    catch (Exception ex)
                    {                           
                        System.Windows.MessageBox.Show(ex.ToString());
                    }
                }
            }
            catch (Exception ex)
            {

                System.Windows.MessageBox.Show(ex.Message);
            }

        }

        public void onExitRoom(int reason)
        {
            if(mStopSharingDesktopForm != null && !mStopSharingDesktopForm.IsDisposed)
                mStopSharingDesktopForm.Close();

            mIsEnterSuccess = false;
            Uninit();
            this.Close();
        }

        private void Uninit(bool needSendCloseMsg = true)
        {
            if (isscene1 == "1" || TCommon.AppContext.startFromOldVersion)
            {
                string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":11,\"userid\":\"{2}\"{3}", "{", TRTC.VideoMainForm.roomId1, name, "}");
                fasongmessage(inputMsg);
                if (TCommon.AppContext.VirtualCamera != null)
                {
                    TCommon.AppContext.VirtualCamera.StopCaptureScreen();
                    mTRTCCloud.stopSystemAudioLoopback();
                }
            }
            //if (TCommon.AppContext.isHost == true)
            //{
            //    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":102{2}", "{", roomId, "}");
            //    fasongmessage(inputMsg);
            //}
            if (isPhilipMode) {
                if (recordForm != null)
                {
                    NoteChanged?.Invoke(recordForm.GetServiceId(), recordForm.GetNote());
                }
            }
            clear();
            videoContainer.clearNormalScreenUsers();
            userList.clearNormalScreenUsers();
            if (threadTimer != null)
            {
                threadTimer.Dispose();
            }

            if (role == UserRole.Host && needSendCloseMsg)
            {
                var action = new ActionEntity()
                {
                    ActionId = HostAction.CloseMeeting,
                };
                var jsonString = JsonConvert.SerializeObject(action);
                var data = Encoding.UTF8.GetBytes(jsonString);
                mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                TerminateMeeting(this.roomId);
            }
            mMixStreamVideoMeta.Clear();
            mRoomUsers.Clear();
            mTRTCCloud.removeCallback(this);
            mTRTCCloud.setLogCallback(null);
            //if (this.systemAudioCheckBox.Checked)
            mTRTCCloud.stopSystemAudioLoopback();
            if (this.shareButton.IsChecked)
                mTRTCCloud.stopScreenCapture();
            //if (this.systemAudioCheckBox.Checked)
            mTRTCCloud.stopSystemAudioLoopback();
            //if (this.mixTransCodingCheckBox.Checked)
            mTRTCCloud.setMixTranscodingConfig(null);
            mTRTCCloud.exitRoom();

            if (!isPhilipMode)
            {
                client.MessageReceived -= MessageReceived;
                Task.Factory.StartNew(new Action(() =>
                {
                    Thread.Sleep(1000);
                    client.Stop();
                }));
            }

            if (TCommon.AppContext.startFromOldVersion)
            {
                this.loginWindow11?.Close();
            }
            else
            {
                this.loginWindow11?.Show();
            }

            mStopSharingDesktopForm?.Close();
            TCommon.AppContext.MessageBoard.Close();
            TCommon.AppContext.IsOnMic = false;
            TCommon.AppContext.AllowChat = true;
            TCommon.AppContext.OpenTanMu = true;
            TCommon.AppContext.isMuted = false;
            TCommon.AppContext.FocusedUser = string.Empty;
            TCommon.AppContext.isSharingScreen = false;
        }

        public void onSwitchRole(TXLiteAVError errCode, string errMsg)
        {
            //throw new NotImplementedException();
        }

        public void onConnectOtherRoom(string userId, TXLiteAVError errCode, string errMsg)
        {
            //throw new NotImplementedException();
        }

        public void onDisconnectOtherRoom(TXLiteAVError errCode, string errMsg)
        {
            //throw new NotImplementedException();
        }

        public void onUserEnter(string userId)
        {
            if(!mRoomUsers.Contains(userId))
                mRoomUsers.Add(userId);
                videoContainer.GetVideoHandle(userId);
            if (this.role == UserRole.Host)
            {
                if (this.stopShareButton.IsChecked == false)
                {
                    var action = new ActionEntity()
                    {
                        ActionId = HostAction.StopShare
                    };
                    var actionString = JsonConvert.SerializeObject(action);
                    var data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                }

                if (this.muteAllButton.IsChecked == false)
                {
                    var action = new ActionEntity()
                    {
                        ActionId = HostAction.MuteAll
                    };
                    var actionString = JsonConvert.SerializeObject(action);
                    var data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                }

                if (!TCommon.AppContext.AllowChat) {
                    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2}{3}", "{", TRTC.VideoMainForm.roomId1, 127, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                }

                if (!TCommon.AppContext.AllowOnMic) {
                    var inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2}{3}", "{", TRTC.VideoMainForm.roomId1, 129, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                }
            }
        }

        public void onUserExit(string userId, int reason)
        {
            foreach (string user in mRoomUsers)
            {
                if (user.Equals(userId))
                {
                    if (isscene1 == "1" || isscene1 == "2")
                    {
                        userList.UpdateMicroOn(userId, false);
                    }
                    else
                    {
                        mRoomUsers.Remove(user);
                        userList.RemoveUer(user);
                    }
                    break;
                }
            }

            videoContainer.RemoveUser(userId);

            int pos = FindOccupyRemoteVideoPosition(userId, true);
            if (pos != -1)
            {
                mTRTCCloud.stopRemoteView(userId);
                mTRTCCloud.stopRemoteSubStreamView(userId);
            }
        }

        public void onUserVideoAvailable(string userId, bool available)
        {
            if (IsMainThread())
                OnUserVideoAvailable(userId, available);
            else
                this.BeginInvoke(new System.Action(() =>
                {
                    OnUserVideoAvailable(userId, available);
                }));
        }

        private void OnUserVideoAvailable(string userId, bool available)
        {
            userList.UpdateVideoStatus(userId, available);
            videoContainer.UpdateVideoUserCameraStatus(userId, !available);
            bool isExit = mRoomUsers.Exists((user) =>
            {
                if (user.Equals(userId)) return true;
                else return false;
            });
            if (!isExit) return;
            if (available)
            {
                int pos = GetIdleRemoteVideoPosition(userId);
                if (pos != -1)
                {
                    IntPtr ptr = GetHandleAndSetUserId(userId, false);
                    SetVisableInfoView(pos, false);
                    mTRTCCloud.setRemoteViewFillMode(userId, TRTCVideoFillMode.TRTCVideoFillMode_Fit);
                    mTRTCCloud.startRemoteView(userId, ptr);
                }
            }
            else
            {
                int pos = GetRemoteVIdeoPosition(userId);
                if (pos != -1)
                {
                    SetVisableInfoView(pos, true);
                    mTRTCCloud.stopRemoteView(userId);
                    RemoveVideoMeta(userId, TRTCVideoStreamType.TRTCVideoStreamTypeBig);
                    UpdateMixTranCodeInfo();
                }
            }
        }

        private int GetRemoteVIdeoPosition(String userId)
        {
            return 1;
        }

        public void onUserSubStreamAvailable(string userId, bool available)
        {
            if (IsMainThread())
                OnUserSubStreamAvailable(userId, available);
            else
                this.BeginInvoke(new System.Action(() =>
                {
                    OnUserSubStreamAvailable(userId, available);
                }));
        }

        private bool IsMainThread()
        {
            return System.Threading.Thread.CurrentThread.ManagedThreadId == mainThreadId;
        }

        public void onUserAudioAvailable(string userId, bool available)
        {
            if (available)
            {
                mTRTCCloud.muteRemoteAudio(userId, false);
            }
            else
            {
                mTRTCCloud.muteRemoteAudio(userId, true);
            }

            if (IsMainThread())
            {
                userList.UpdateAudioStatus(userId, available);
                videoContainer.UpdateVideoUserMicroStatus(userId, !available);
            }
            else
                this.BeginInvoke(new System.Action(() =>
                {
                    userList.UpdateAudioStatus(userId, available);
                    videoContainer.UpdateVideoUserMicroStatus(userId, !available);
                }));
        }

        public void onFirstVideoFrame(string userId, TRTCVideoStreamType streamType, int width, int height)
        {
            if (!this.shareButton.IsChecked)
            {
                if (string.IsNullOrEmpty(userId) && streamType == TRTCVideoStreamType.TRTCVideoStreamTypeSub)
                    return;
            }
            if (!string.IsNullOrEmpty(userId))
            {
                // 暂时只支持最多6个人同时视频
                if (streamType == TRTCVideoStreamType.TRTCVideoStreamTypeBig && FindOccupyRemoteVideoPosition(userId, false) == -1)
                    return;
                if (streamType == TRTCVideoStreamType.TRTCVideoStreamTypeSub && FindOccupyRemoteVideoPosition(userId + "(屏幕分享)", false) == -1)
                    return;
            }
            if (string.IsNullOrEmpty(userId)) userId = mUserId;
            bool find = false;
            foreach (UserVideoMeta info in mMixStreamVideoMeta)
            {
                if (info.userId.Equals(userId) && info.streamType == streamType)
                {
                    info.width = width;
                    info.height = height;
                    find = true;
                    break;
                }
            }
            if (!find && !(streamType == TRTCVideoStreamType.TRTCVideoStreamTypeBig && userId == mUserId))
            {
                UserVideoMeta info = new UserVideoMeta();
                info.streamType = streamType;
                info.userId = userId;
                info.width = width;
                info.height = height;
                mMixStreamVideoMeta.Add(info);
                //UpdateMixTranCodeInfo();
            }
            else
            {
                if (userId != mUserId)
                    UpdateMixTranCodeInfo();
            }
        }

        public void onFirstAudioFrame(string userId)
        {
            //throw new NotImplementedException();
        }

        public void onSendFirstLocalVideoFrame(TRTCVideoStreamType streamType)
        {
            //throw new NotImplementedException();
        }

        public void onSendFirstLocalAudioFrame()
        {
            //throw new NotImplementedException();
        }

        public void onNetworkQuality(TRTCQualityInfo localQuality, TRTCQualityInfo[] remoteQuality, uint remoteQualityCount)
        {
            //throw new NotImplementedException();
        }

        public void onStatistics(TRTCStatistics statis)
        {
            //throw new NotImplementedException();
        }

        public void onConnectionLost()
        {
            //throw new NotImplementedException();
        }

        public void onTryToReconnect()
        {
            //throw new NotImplementedException();
        }

        public void onConnectionRecovery()
        {
            //throw new NotImplementedException();
        }

        public void onSpeedTest(TRTCSpeedTestResult currentResult, uint finishedCount, uint totalCount)
        {
            //throw new NotImplementedException();
        }

        public void onCameraDidReady()
        {
            mCurCameraDevice = mTRTCCloud.getCurrentCameraDevice().getDeviceName();
        }

        public void onMicDidReady()
        {
            mCurMicDevice = mTRTCCloud.getCurrentMicDevice().getDeviceName();
        }

        public void onUserVoiceVolume(TRTCVolumeInfo[] userVolumes, uint userVolumesCount, uint totalVolume)
        {
            //var info = userVolumes.OrderByDescending(t => t.volume).FirstOrDefault();

            //if (volumeControl == null)
            //{
            //    volumeControl = new VolumeControl();
            //    this.Controls.Add(volumeControl);
            //    volumeControl.Location = new System.Drawing.Point(5, 5);
            //    volumeControl.UserNameClicked += VolumeControl_UserNameClicked;
            //}

            //if (info != null && info.volume > 3)
            //{
            //    if (string.IsNullOrEmpty(info.userId))
            //    {
            //        var name = StringUtil.UnHex(this.name);
            //        if (!string.IsNullOrEmpty(name)) {
            //            var array = name.Split(':');
            //            if (array.Length > 1) {
            //                var endStr = array[array.Length - 1];
            //                name = name.Substring(0, name.Length - endStr.Length -1);
            //            }
            //        }
            //        volumeControl.SetUserName(name, this.name);
            //    }
            //    else
            //    {
            //        var name = StringUtil.UnHex(info.userId);
            //        if (!string.IsNullOrEmpty(name))
            //        {
            //            var array = name.Split(':');
            //            if (array.Length > 1)
            //            {
            //                var endStr = array[array.Length - 1];
            //                name = name.Substring(0, name.Length - endStr.Length-1);
            //            }
            //        }
            //        volumeControl.SetUserName(name, info.userId);
            //    }
            //    volumeControl.Visible = true;
            //    speakTime = DateTime.Now;
            //    volumeControl.BringToFront();
            //}
            //else {
            //    if ((DateTime.Now - speakTime).Seconds > 3) {
            //        volumeControl.Visible = false;
            //    }              
            //}
        }

        private void VolumeControl_UserNameClicked(string userid)
        {
            if (!string.IsNullOrEmpty(userid)) {
                videoContainer.SetFocuseUser(userid);
            }
        }

        public void onDeviceChange(string deviceId, TRTCDeviceType type, TRTCDeviceState state)
        {
            try
            {
                if (type == TRTCDeviceType.TRTCDeviceTypeCamera)
                {
                    this.BeginInvoke(new System.Action(() =>
                    {
                        RefreshVideoDevice(deviceId, state);
                    }));

                }
                else if (type == TRTCDeviceType.TRTCDeviceTypeMic)
                {
                    this.BeginInvoke(new System.Action(() =>
                    {
                        RefreshAudioDevice(deviceId, state);
                    }));
                }
                this.BeginInvoke(new System.Action(() =>
                {
                    //if (mDeviceForm != null)
                    //    mDeviceForm.OnDeviceChange(deviceId, type, state);
                }));
            }
            catch (Exception ex)
            {

                System.Windows.MessageBox.Show(ex.ToString());
            }
        }

        private void RefreshAudioDevice(string deviceId, TRTCDeviceState state)
        {
            bool reSelectDevice = false;
            ITRTCDeviceCollection collection = mTRTCCloud.getMicDevicesList();
            if (state == TRTCDeviceState.TRTCDeviceStateRemove)
            {
                // 选择设备被移除了，此时可能还有其他设备
                if (mCurMicDevice.Equals(deviceId))
                {
                    reSelectDevice = true;
                }
                // 有设备变成没设备
                if (!string.IsNullOrEmpty(mCurMicDevice) && collection.getCount() <= 0)
                {
                    ShowMessage("Error: 未检出到麦克风，请检查本地电脑设备。");
                    //Log.I("Error: 未检出到麦克风，请检查本地电脑设备。");
                    mCurMicDevice = "";
                    return;
                }
            }
            else if (state == TRTCDeviceState.TRTCDeviceStateAdd)
            {
                // 没有设备变成有设备
                if (string.IsNullOrEmpty(mCurMicDevice))
                {
                    reSelectDevice = true;
                }
            }

            if (reSelectDevice)
            {
                // 选择第一个设备为当前使用设备
                if (collection.getCount() > 0)
                {
                    mTRTCCloud.setCurrentMicDevice(collection.getDevicePID(0));
                    mTRTCCloud.startLocalAudio();
                    mCurMicDevice = collection.getDeviceName(0);
                }
            }
            collection.release();
        }

        private void RefreshVideoDevice(string deviceId, TRTCDeviceState state)
        {
            bool reSelectDevice = false;

            if (state == TRTCDeviceState.TRTCDeviceStateRemove)
            {
                // 选择设备被移除了，此时可能还有其他设备
                if (mCurCameraDevice.Equals(deviceId))
                {
                    reSelectDevice = true;
                }
                // 有设备变成没设备
                if (!string.IsNullOrEmpty(mCurCameraDevice) && mTRTCCloud.getCameraDevicesList().getCount() <= 0)
                {
                    ShowMessage("Error: 未检出到摄像头，请检查本地电脑设备。");
                    //Log.I("Error: 未检出到摄像头，请检查本地电脑设备。");
                    mCurCameraDevice = "";
                    return;
                }
            }
            else if (state == TRTCDeviceState.TRTCDeviceStateAdd)
            {
                // 没有设备变成有设备
                if (string.IsNullOrEmpty(mCurCameraDevice))
                {
                    reSelectDevice = true;
                }
            }

            if (reSelectDevice)
            {
                // 选择第一个设备为当前使用设备
                ITRTCDeviceCollection collection = mTRTCCloud.getCameraDevicesList();
                if (collection.getCount() > 0)
                {
                    mTRTCCloud.setCurrentCameraDevice(collection.getDevicePID(0));
                    mTRTCCloud.startLocalPreview(mCameraLocalVideo);
                    mCurCameraDevice = collection.getDeviceName(0);
                }
                collection.release();
            }
        }

        public void onTestMicVolume(uint volume)
        {
            //throw new NotImplementedException();
        }

        public void onTestSpeakerVolume(uint volume)
        {
            //throw new NotImplementedException();
        }

        public void onRecvCustomCmdMsg(string userId, int cmdId, uint seq, byte[] msg, uint msgSize)
        {
            HandleCustomMessage(cmdId, userId, msg);
        }
        int sum = 0;
        private void HandleCustomMessage(int cmdId, string userId, byte[] msg)
        {
            //try
            //{
            switch ((uint)cmdId)
            {
                case MessageId.RaiseHand:
                    if (IsMainThread())
                    {
                        userList.UpdateHandStatus(userId, true);
                    }
                    else
                        this.BeginInvoke(new System.Action(() =>
                        {
                            userList.UpdateHandStatus(userId, true);
                        }));

                    break;
                case MessageId.DownHand:
                    this.BeginInvoke(new System.Action(() =>
                    {
                        userList.UpdateHandStatus(userId, false);
                    }));                    
                    break;
                case MessageId.ChangeName:
                    var nameStr = Encoding.UTF8.GetString(msg);
                    var nameAction = JsonConvert.DeserializeObject<ActionEntity>(nameStr);
                    if (IsMainThread())
                        userList.UpdateUserName(nameAction.UserId, nameAction.UserName);
                    else
                        this.BeginInvoke(new System.Action(() =>
                        {
                            userList.UpdateUserName(nameAction.UserId, nameAction.UserName);
                        }));
                    break;
                case MessageId.HostAction:
                    var msgStr = Encoding.UTF8.GetString(msg);
                    var action = JsonConvert.DeserializeObject<ActionEntity>(msgStr);
                    HandleHostAction(action);
                    break;
                case MessageId.SendDanmu:
                    var danStr = Encoding.UTF8.GetString(msg);
                    var tanmuAction = JsonConvert.DeserializeObject<DanMuEntity>(danStr);
                    string name = StringUtil.UserNameFromHex(userId);
                    AddTanMu(name + "：" + tanmuAction.Text);
                    break;
            }
            // }
            //catch (Exception ex)
            //{

            //    System.Windows.MessageBox.Show(ex.Message);
            //}
        }
        [System.Runtime.InteropServices.DllImport("user32.dll ")]
        public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int wndproc);
        [System.Runtime.InteropServices.DllImport("user32.dll ")]
        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
        public const int GWL_STYLE = -16;
        public const int WS_DISABLED = 0x8000000;
        public static void SetControlEnabled(Control c, bool enabled)
        {
            if (enabled)
            { SetWindowLong(c.Handle, GWL_STYLE, (~WS_DISABLED) & GetWindowLong(c.Handle, GWL_STYLE)); }
            else
            { SetWindowLong(c.Handle, GWL_STYLE, WS_DISABLED | GetWindowLong(c.Handle, GWL_STYLE)); }
        }

        private void HandleHostAction(ActionEntity action)
        {
            var userId = action.UserId;
            switch (action.ActionId)
            {
                case HostAction.MuteUser:
                    if (userId == this.name && !TCommon.AppContext.isHost)
                    {
                        this.microButton.IsChecked = false;
                        mTRTCCloud.muteLocalAudio(true);
                        userList.UpdateAudioStatus(this.name, false);
                        //SetControlEnabled(this.microButton, false);
                        this.microButton.label.ForeColor = Color.White;
                        TCommon.AppContext.isMuted = true;
                    }
                    break;
                case HostAction.UnMuteUser:
                    if (userId == this.name)
                    {
                        if (cachMicroBtnStatus)
                        {
                            this.microButton.IsChecked = true;
                            mTRTCCloud.muteLocalAudio(false);
                            userList.UpdateAudioStatus(this.name, true);
                            //SetControlEnabled(this.microButton, true);
                            this.microButton.label.ForeColor = Color.White;
                        }
                        TCommon.AppContext.isMuted = false;
                    }
                    break;
                case HostAction.DownUserHand:
                    if (userId == this.name && handButton.IsChecked == true)
                    {
                        this.handButton.IsChecked = false;
                    }
                    break;
                case HostAction.RemoveUser:
                    if (userId == this.name)
                    {
                        Uninit();
                        ShowClosePrompt = false;
                        this.Close();
                        this.loginWindow11?.Show();
                        System.Windows.MessageBox.Show("您被移出了会议");
                    }
                    break;
                case HostAction.StopShare:
                    if (shareButton.IsChecked == true)
                    {
                        shareButton.IsChecked = false;
                    }
                    // shareButton.Enabled = false;
                    shareButton.changepic(true);
                    SetControlEnabled(this.shareButton, false);
                    this.shareButton.label.ForeColor = Color.White;
                    break;
                case HostAction.AllowShare:
                    //shareButton.Enabled = true;
                    shareButton.changepic(false);
                    SetControlEnabled(this.shareButton, true);
                    this.shareButton.label.ForeColor = Color.White;
                    break;
                case HostAction.DownAllHand:
                    if (handButton.IsChecked == true)
                    {
                        handButton.IsChecked = false;
                    }
                    break;
                case HostAction.FocuseUser:
                    if (!TCommon.AppContext.isHost)
                    {
                        userList.SetFocuseUser(userId);
                    }
                    videoContainer.SetFocuseUser(userId);
                    //FocusUserChanged?.Invoke(this, userId);                 
                    Focuse = userId;
                    break;
                case HostAction.MuteAll:
                    if (!TCommon.AppContext.isHost)
                    {
                        microButton.IsChecked = false;
                        mTRTCCloud.muteLocalAudio(true);
                        userList.UpdateAudioStatus(this.name, false);
                        TCommon.AppContext.isMuted = true;
                        //SetControlEnabled(this.microButton, false);

                        //microButton.Enabled = false;
                    }
                    break;
                case HostAction.UnMuteAll:
                    if (cachMicroBtnStatus)
                    {
                        microButton.IsChecked = true;
                        mTRTCCloud.muteLocalAudio(false);
                        userList.UpdateAudioStatus(this.name, true);
                        //SetControlEnabled(this.microButton, true);
                        this.microButton.label.ForeColor = Color.White;
                    }
                    TCommon.AppContext.isMuted = false;
                    break;
                case HostAction.OpenAllVideo:
                    if (this.role != UserRole.Host)
                        cameraButton.IsChecked = true;
                    break;
                case HostAction.CloseAllVideo:
                    if (this.role != UserRole.Host)
                        cameraButton.IsChecked = false;
                    break;
                case HostAction.OpenUserVideo:
                    if (userId == this.name)
                        cameraButton.IsChecked = true;
                    break;
                case HostAction.CloseUserVideo:
                    if (userId == this.name)
                        cameraButton.IsChecked = false;
                    break;
                case HostAction.CloseMeeting:
                    videoContainer.clearNormalScreenUsers();
                    userList.clearNormalScreenUsers();
                    Uninit();
                    ShowClosePrompt = false;
                    this.Close();
                    if (TCommon.AppContext.startFromOldVersion)
                    {
                        this.loginWindow11?.Close();
                    }
                    else
                    {
                        this.loginWindow11?.Show();
                        System.Windows.MessageBox.Show("主持人结束了会议");
                    }
                    break;
                case HostAction.MeetingTimeout:
                    videoContainer.clearNormalScreenUsers();
                    userList.clearNormalScreenUsers();
                    //string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":102{2}", "{", roomId, "}");
                    //fasongmessage(inputMsg);
                    Uninit();
                    ShowClosePrompt = false;
                    this.Close();
                    this.loginWindow11?.Show();
                    System.Windows.MessageBox.Show("会议时间已用完,会议自动结束");
                    break;
                case HostAction.NoChat:
                    if (!TCommon.AppContext.isHost)
                    {
                        SetControlEnabled(chatButton1, false);
                    }
                    break;
                case HostAction.AllowChat:
                    if (!TCommon.AppContext.isHost)
                    {
                        SetControlEnabled(chatButton1, true);
                    }
                    break;
            }
        }

        public void onMissCustomCmdMsg(string userId, int cmdId, int errCode, int missed)
        {
            //throw new NotImplementedException();
        }

        public void onRecvSEIMsg(string userId, byte[] message, uint msgSize)
        {
            //throw new NotImplementedException();
        }

        public void onStartPublishCDNStream(int errCode, string errMsg)
        {
            //throw new NotImplementedException();
        }

        public void onStopPublishCDNStream(int errCode, string errMsg)
        {
            //throw new NotImplementedException();
        }

        public void onSetMixTranscodingConfig(int errCode, string errMsg)
        {

        }

        public void onScreenCaptureCovered()
        {
            //throw new NotImplementedException();
        }

        public void onScreenCaptureStarted()
        {
            //throw new NotImplementedException();
        }

        public void onScreenCapturePaused(int reason)
        {
            //throw new NotImplementedException();
        }

        public void onScreenCaptureResumed(int reason)
        {
            //throw new NotImplementedException();
        }

        public void onScreenCaptureStoped(int reason)
        {
            //throw new NotImplementedException();
        }

        public void onPlayBGMBegin(TXLiteAVError errCode)
        {
            //throw new NotImplementedException();
        }

        public void onPlayBGMProgress(uint progressMS, uint durationMS)
        {
            //throw new NotImplementedException();
        }

        public void onPlayBGMComplete(TXLiteAVError errCode)
        {
            //throw new NotImplementedException();
        }
        
        private void UserList_HandCountChanged(int count)
        {
            if (count > 0)
            {
                raiseCount1.Visible = true;
            }
            else {
                raiseCount1.Visible = false;
            }
            raiseCount1.UpdateHandCount(count);
        }

        

        public void CloseMeeting() {
            if (isscene1 == "1" || TCommon.AppContext.startFromOldVersion)
            {
                string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":11,\"userid\":\"{2}\"{3}", "{", TRTC.VideoMainForm.roomId1, name, "}");
                fasongmessage(inputMsg);
            }

            clear();
            videoContainer.clearNormalScreenUsers();
            userList.clearNormalScreenUsers();
            if (threadTimer != null)
            {
                threadTimer.Dispose();
            }
            Uninit();
            if (TCommon.AppContext.startFromOldVersion)
            {
                this.loginWindow11?.Close();
            }
            else
            {
                this.loginWindow11?.Show();
            }
        }

        public void SendDanMu(string msg) {
            if (isscene1 == "1" || isscene1 == "2")
            {
                string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\",\"txt\":\"{4}\"{5}", "{", TRTC.VideoMainForm.roomId1, 9, TRTC.VideoMainForm.name1, msg, "}");
                TRTC.VideoMainForm.fasongmessage(inputMsg);
            }
            else
            {
                var action = new DanMuEntity()
                {
                    ActionId = 0,
                    UserId = this.name,
                    Text = msg
                };
                //var actionString = JsonConvert.SerializeObject(action);
                string actionString = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\",\"txt\":\"{4}\"{5}", "{", TRTC.VideoMainForm.roomId1, 9, this.name, msg, "}");
                var data = Encoding.UTF8.GetBytes(actionString);
                mTRTCCloud.sendCustomCmdMsg(MessageId.SendDanmu, data, (uint)data.Length, true, true);
                string name = StringUtil.UserNameFromHex(this.name);
                AddTanMu(name + "：" + msg);
            }
        }

        private Form loginWindow11;

        #region
        public VideoMainForm(Form loginWindow12, int roomId, string userName, string hostId, string userSign, UserRole role = UserRole.Participant)
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);
            this.loginWindow11 = loginWindow12;

            this.roomId = roomId;
            this.name = userName;
            this.role = role;
            this.UserSign = userSign;
            this.HostId = hostId;
            TCommon.AppContext.isHost = role == UserRole.Host;
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
            InitializeComponent();
            upanddownwheat1.Visible = false;
            this.Text = $"OneMeeting 会议号：{roomId}";
            userList.UserCountChanged += UserList_UserCountChanged;
            userList.SetCurrentUser(userName);
            userList.ViewUserVideoClicked += UserList_ViewUserVideoClicked;
            userList.FocuseUserClicked += UserList_FocuseUserClicked;
            videoContainer.ButtonChanged += VideoContainer_ButtonChanged;
            videoContainer.VideoLayoutChanged += VideoContainer_VideoLayoutChanged;
            videoContainer.FullScreenChanged += VideoContainer_FullScreenChanged;
            videoContainer.FocusedUserChanged += VideoContainer_FocusedUserChanged;
            videoContainer.HostName = hostId;
            if (this.role == UserRole.Host)
            {
                userList.SetHost();
                userList.HandChanged += UserList_HandChanged;
                userList.HandCountChanged += UserList_HandCountChanged;
            }
            if (role == UserRole.Host)
            {
                this.handButton.Visible = false;
                livesButton1.Visible = true;
            }
            else
            {
                //this.closeMeetingButton.Visible = false;
                this.muteAllButton.Visible = false;
                this.stopShareButton.Visible = false;
                this.dwonAllHandButton.Visible = false;
                livesButton1.Visible = false;
                //this.openAllVideo.Visible = false;//视屏开关
                //this.closeAllVideo.Visible = false;
            }

            this.Disposed += new EventHandler(OnDisposed);

            mTRTCCloud = ITRTCCloud.getTRTCShareInstance();
            //Log.I(String.Format(" SDKVersion : {0}", mTRTCCloud.getSDKVersion()));
            mTRTCCloud.addCallback(this);
            mTRTCCloud.setLogCallback(this);
            mTRTCCloud.setConsoleEnabled(true);
            mTRTCCloud.setLogLevel(TRTCLogLevel.TRTCLogLevelVerbose);
            videoContainer.SetClound(mTRTCCloud);
            mMixStreamVideoMeta = new List<UserVideoMeta>();
            mRoomUsers = new List<string>();
        }

        private void VideoContainer_FocusedUserChanged(string userId)
        {
            userList.SetFocuseUser(userId);
        }

        public VideoMainForm(int roomId, string userName, string hostId, string userSign, UserRole role = UserRole.Participant)
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);

            this.roomId = roomId;
            this.name = userName;
            this.role = role;
            this.UserSign = userSign;
            this.HostId = hostId;
            TCommon.AppContext.isHost = role == UserRole.Host;
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
            InitializeComponent();
            upanddownwheat1.Visible = false;
            this.Text = $"OneMeeting 会议号：{roomId}";
            userList.UserCountChanged += UserList_UserCountChanged;
            userList.SetCurrentUser(userName);
            userList.ViewUserVideoClicked += UserList_ViewUserVideoClicked;
            userList.FocuseUserClicked += UserList_FocuseUserClicked;
            videoContainer.ButtonChanged += VideoContainer_ButtonChanged;
            videoContainer.VideoLayoutChanged += VideoContainer_VideoLayoutChanged;
            videoContainer.FullScreenChanged += VideoContainer_FullScreenChanged;
            videoContainer.HostName = hostId;
            if (this.role == UserRole.Host)
            {
                userList.SetHost();
                userList.HandChanged += UserList_HandChanged;
                userList.HandCountChanged += UserList_HandCountChanged;
            }
            if (role == UserRole.Host)
            {
                this.handButton.Visible = false;
            }
            else
            {
                //this.closeMeetingButton.Visible = false;
                this.muteAllButton.Visible = false;
                this.stopShareButton.Visible = false;
                this.dwonAllHandButton.Visible = false;
                //this.openAllVideo.Visible = false;//视屏开关
                //this.closeAllVideo.Visible = false;
            }

            this.Disposed += new EventHandler(OnDisposed);

            mTRTCCloud = ITRTCCloud.getTRTCShareInstance();
            //Log.I(String.Format(" SDKVersion : {0}", mTRTCCloud.getSDKVersion()));
            mTRTCCloud.addCallback(this);
            mTRTCCloud.setLogCallback(this);
            mTRTCCloud.setConsoleEnabled(true);
            mTRTCCloud.setLogLevel(TRTCLogLevel.TRTCLogLevelVerbose);
            videoContainer.SetClound(mTRTCCloud);
            mMixStreamVideoMeta = new List<UserVideoMeta>();
            mRoomUsers = new List<string>();

            //ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false);
        }

        //主播直播模式
        public VideoMainForm(Form loginWindow12, int roomId, bool islive, string userName, string hostId, string userSign, UserRole role = UserRole.Participant)
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);
            this.loginWindow11 = loginWindow12;

            islive1 = islive;
            isscene1 = "2";
            this.roomId = roomId;
            this.name = userName;
            this.role = role;
            this.UserSign = userSign;
            this.HostId = hostId;
            TCommon.AppContext.isHost = role == UserRole.Host;
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
            InitializeComponent();
            upanddownwheat1.Visible = false;
            this.Text = $"OneMeeting 会议号：{roomId}";
            userList.UserCountChanged += UserList_UserCountChanged;
            userList.SetCurrentUser(userName);
            userList.ViewUserVideoClicked += UserList_ViewUserVideoClicked;
            userList.FocuseUserClicked += UserList_FocuseUserClicked;
            videoContainer.ButtonChanged += VideoContainer_ButtonChanged;
            videoContainer.VideoLayoutChanged += VideoContainer_VideoLayoutChanged;
            videoContainer.FullScreenChanged += VideoContainer_FullScreenChanged;
            videoContainer.HostName = hostId;
            if (this.role == UserRole.Host)
            {
                userList.SetHost();
                userList.HandChanged += UserList_HandChanged;
                userList.HandCountChanged += UserList_HandCountChanged;
            }
            if (role == UserRole.Host)
            {
                this.handButton.Visible = false;
            }
            else
            {
                //this.closeMeetingButton.Visible = false;
                this.muteAllButton.Visible = false;
                this.stopShareButton.Visible = false;
                this.dwonAllHandButton.Visible = false;
                //this.openAllVideo.Visible = false;//视屏开关
                //this.closeAllVideo.Visible = false;
            }

            this.Disposed += new EventHandler(OnDisposed);

            mTRTCCloud = ITRTCCloud.getTRTCShareInstance();
            //Log.I(String.Format(" SDKVersion : {0}", mTRTCCloud.getSDKVersion()));
            mTRTCCloud.addCallback(this);
            mTRTCCloud.setLogCallback(this);
            mTRTCCloud.setConsoleEnabled(true);
            mTRTCCloud.setLogLevel(TRTCLogLevel.TRTCLogLevelVerbose);
            videoContainer.SetClound(mTRTCCloud);
            mMixStreamVideoMeta = new List<UserVideoMeta>();
            mRoomUsers = new List<string>();
            PropertySaver.GetInstance().appScene = TRTCAppScene.TRTCAppSceneLIVE;
            currentRole = TRTCRoleType.TRTCRoleAnchor;
        }

        //观众进入直播模式
        public VideoMainForm(Form loginWindow12, int roomId, string isscene, string userName, string hostId, string userSign, UserRole role = UserRole.Participant)
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);
            this.loginWindow11 = loginWindow12;
            isscene1 = isscene;
            this.roomId = roomId;
            this.name = userName;
            this.role = role;
            this.UserSign = userSign;
            this.HostId = hostId;
            TCommon.AppContext.isHost = role == UserRole.Host;
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
            InitializeComponent();
            if (isscene != "1")
            {
                upanddownwheat1.Visible = false;
                handButton.Location = new System.Drawing.Point(517, -1);
            }
            else
            {
                PropertySaver.GetInstance().appScene = TRTCAppScene.TRTCAppSceneLIVE;
                currentRole = TRTCRoleType.TRTCRoleAudience;
            }

            this.Text = $"OneMeeting 会议号：{roomId}";
            userList.UserCountChanged += UserList_UserCountChanged;

            userList.SetCurrentUser(userName);
            userList.ViewUserVideoClicked += UserList_ViewUserVideoClicked;
            userList.FocuseUserClicked += UserList_FocuseUserClicked;
            videoContainer.ButtonChanged += VideoContainer_ButtonChanged;
            videoContainer.VideoLayoutChanged += VideoContainer_VideoLayoutChanged;
            videoContainer.FullScreenChanged += VideoContainer_FullScreenChanged;
            videoContainer.HostName = hostId;
            if (this.role == UserRole.Host)
            {
                userList.SetHost();
                userList.HandChanged += UserList_HandChanged;
                userList.HandCountChanged += UserList_HandCountChanged;
            }
            if (role == UserRole.Host)
            {
                this.handButton.Visible = false;
                this.livesButton1.Visible = true;
            }
            else
            {
                //this.closeMeetingButton.Visible = false;
                this.muteAllButton.Visible = false;
                this.stopShareButton.Visible = false;
                this.dwonAllHandButton.Visible = false;
                //this.openAllVideo.Visible = false;//视屏开关
                //this.closeAllVideo.Visible = false;
                this.livesButton1.Visible = false;
            }

            this.Disposed += new EventHandler(OnDisposed);

            mTRTCCloud = ITRTCCloud.getTRTCShareInstance();
            //Log.I(String.Format(" SDKVersion : {0}", mTRTCCloud.getSDKVersion()));
            mTRTCCloud.addCallback(this);
            mTRTCCloud.setLogCallback(this);
            mTRTCCloud.setConsoleEnabled(true);
            mTRTCCloud.setLogLevel(TRTCLogLevel.TRTCLogLevelVerbose);
            videoContainer.SetClound(mTRTCCloud);
            mMixStreamVideoMeta = new List<UserVideoMeta>();
            mRoomUsers = new List<string>();
        }

        //飞利浦模式专用 //TODO 改成通用方法，可以根据不同需求配置UI
        public void SetPhilipsMode(long serviceId = -1, GetDeviceInfoResponse res = null)
        {
            layoutButton1.Visible = false;
            chatButton1.Visible = false;
            handButton.Visible = false;
            livesButton1.Visible = false;
            stopShareButton.Visible = false;
            muteAllButton.Visible = false;
            upanddownwheat1.Visible = false;
            shareButton.Location = new System.Drawing.Point(200, 0);
            usersButton.Location = new System.Drawing.Point(270, 0);
            settingButton.Location = new System.Drawing.Point(340, 0);
            var record_btn = new RecordButton();
            record_btn.Location = new System.Drawing.Point(410, 0);
            record_btn.BtnClicked += Record_btn_BtnClicked;
            var devive_btn = new DeviceButton();
            devive_btn.Location = new System.Drawing.Point(480, 0);
            devive_btn.BtnClicked += Devive_btn_BtnClicked;
            panel.Controls.Add(record_btn);
            panel.Controls.Add(devive_btn);

            isPhilipMode = true;
            ServiceId = serviceId;
            this.deviceInfo = res;
        }

        private void Devive_btn_BtnClicked()
        {
            if (deviceForm == null)
            {
                deviceForm = new DeviceDetailForm(deviceInfo);
            }

            if (deviceForm.Visible)
            {
                deviceForm.Hide();
            }
            else
            {
                deviceForm.Show(this);
                deviceForm.Location = new System.Drawing.Point(this.Location.X + (int)(this.Width - deviceForm.Width) / 2,
                        this.Location.Y + (int)(this.Height - deviceForm.Height) / 2);
            }
        }

        private void Record_btn_BtnClicked()
        {
            if (recordForm == null)
            {
                recordForm = new AppRecordForm(ServiceId);
                recordForm.NoteChanged += RecordForm_NoteChanged;
            }

            if (recordForm.Visible)
            {
                recordForm.Hide();
            }
            else
            {
                recordForm.Show(this);
                recordForm.Location = new System.Drawing.Point(this.Location.X + 15,
                    this.Location.Y + this.Height - recordForm.Height - 65);
            }
        }

        private void RecordForm_NoteChanged(long serviceId, string note)
        {
            NoteChanged?.Invoke(serviceId, note);
        }
        #endregion

        public void VideoContainer_FullScreenChanged(bool isFullScreen)
        {
            try
            {
                if (isFullScreen)
                {
                    if (this.WindowState == FormWindowState.Maximized) {
                        this.WindowState = FormWindowState.Minimized;
                    }
                    //formWidth = this.Width;
                    //formHeight = this.Height;
                    videoContainerWidth = videoContainer.Width;
                    videoContainerHeight = videoContainer.Height;
                    this.FormBorderStyle = FormBorderStyle.None;
                    this.WindowState = FormWindowState.Maximized;
                    //videoContainer.Dock = DockStyle.Fill;
                    videoContainer.Height = videoContainer.Height + panel.Height;
                    this.BackColor = Color.Black;
                    panel.Visible = false;
                }
                else
                {

                    this.FormBorderStyle = FormBorderStyle.Sizable;
                    videoContainer.Dock = DockStyle.None;

                    panel.Visible = true;


                    this.WindowState = FormWindowState.Normal;
                    this.BackColor = Color.Black;
                    Task.Factory.StartNew(new Action(() =>
                    {
                        Thread.Sleep(500);
                        this.Invoke(new Action(() =>
                        {
                            //videoContainer.Width = videoContainerWidth;
                            ////videoContainer.Height = videoContainerHeight;
                            videoContainer.Height = videoContainer.Height - panel.Height;
                            videoContainer.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Right;
                        }));
                    }));

                }
            }
            catch (Exception ex)
            {

                System.Windows.MessageBox.Show(ex.ToString());
            }
        }

        private void VideoContainer_VideoLayoutChanged()
        {
            UpdateMixTranCodeInfo();
        }

        private void VideoContainer_ButtonChanged(bool normalShow, bool smallShow)
        {
            //this.preBtn.Visible = normalShow;
            //this.nextBtn.Visible = normalShow;
            //this.smallNextBtn.Visible = smallShow;
            //this.smallPreBtn.Visible = smallShow;
        }

        private void UserList_UserCountChanged(int count)
        {
            try
            {
                chatControl.SetToUsers(userList.GetAllUserId());
                usersButton.SetUserCount(count);
                if (count > this.Count && this.Count != 0 && role != UserRole.Host
                    && (DateTime.Now - startTime).Milliseconds < 2000)
                {
                    Uninit();
                    ShowClosePrompt = false;
                    this.Close();
                    this.loginWindow11?.Show();
                    System.Windows.MessageBox.Show("参会方数超限");
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
        }

        private void UserList_FocuseUserClicked(string userName)
        {
            videoContainer.SetFocuseUser(userName);
        }

        private void UserList_HandChanged(bool hasHand)
        {
            if (hasHand)
            {
                dwonAllHandButton.Visible = true;
            }
            else
            {
                dwonAllHandButton.Visible = false;
            }
        }

        private void UserList_ViewUserVideoClicked(string userName)
        {
            //videoContainer.ViewUserVideo(userName);
            videoContainer.SetFocuseUser(userName);
        }

        private void OnDisposed(object sender, EventArgs e)
        {
            // 清理资源
            mTRTCCloud = null;
            if (mCameraLocalVideo != IntPtr.Zero)
            {
                mCameraLocalVideo = IntPtr.Zero;
            }
            if (mScreenLocalVideo != IntPtr.Zero)
            {
                mScreenLocalVideo = IntPtr.Zero;
            }
        }

        public void OnSetScreenParamsCallback(bool success)
        {
            mIsSetScreenSuccess = success;
            if (success)
            {
                if (mTRTCCloud != null)
                {
                    mTRTCCloud.startScreenCapture(mScreenLocalVideo);
                }
            }
            else
            {
                this.shareButton.IsChecked = false;
            }
        }

        public void SetTestEnv(int testEnv)
        {
            setNetEnv(testEnv);
        }

        private IntPtr GetHandleAndSetUserId(string userId, bool isOpenSubStream)
        {
            IntPtr ptr;
            if (!isOpenSubStream)
            {
                ptr = videoContainer.GetVideoHandle(userId);
            }
            else
            {
                ptr = videoContainer.GetShareHandle(userId);
            }

            return ptr;
        }

        private void OnUserSubStreamAvailable(string userId, bool available)
        {
            if (available)
            {
                TCommon.AppContext.isSharingScreen = true;
                // 显示远端辅流界面
                int pos = GetIdleRemoteVideoPosition(userId + "(屏幕分享)");
                if (pos != -1)
                {
                    IntPtr ptr = GetHandleAndSetUserId(userId, true);
                    mTRTCCloud.setRemoteSubStreamViewFillMode(userId, TRTCVideoFillMode.TRTCVideoFillMode_Fit);
                    mTRTCCloud.startRemoteSubStreamView(userId, ptr);
                }

                if (userId != this.name)
                {
                    SetControlEnabled(shareButton, false);
                    this.shareButton.label.ForeColor = Color.White;
                }
            }
            else
            {
                TCommon.AppContext.isSharingScreen = false;
                videoContainer.RemoveShareHandle(userId);
                int pos = FindOccupyRemoteVideoPosition(userId + "(屏幕分享)", true);
                if (pos != -1)
                {
                    mTRTCCloud.stopRemoteSubStreamView(userId);
                    RemoveVideoMeta(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSub);
                    UpdateMixTranCodeInfo();
                }

                if (userId != this.name)
                {
                    //shareButton.Enabled = true;
                    SetControlEnabled(this.shareButton, true);
                    this.shareButton.label.ForeColor = Color.White;
                }
            }
        }

        private void UpdateMixTranCodeInfo()
        {
            var locations = videoContainer.GetLocations();
            if (!this.livesButton1.IsChecked)
                return;

            //if (mMixStreamVideoMeta.Count == 0)
            //{
            //    mTRTCCloud.setMixTranscodingConfig(null);
            //    return;
            //}

            if (this.microButton.IsChecked)
            {
                foreach (UserVideoMeta info in mMixStreamVideoMeta)
                    info.pureAudio = true;
            }

            UserVideoMeta localMainVideo = new UserVideoMeta()
            {
                userId = mUserId
            };
            // 连麦后的User可进行设置对应的roomId（暂时未完成连麦）

            int canvasWidth = 960;
            int canvasHeight = 720;
            int appId = GenerateTestUserSig.APPID;
            int bizId = GenerateTestUserSig.BIZID;

            if (appId == 0 || bizId == 0)
            {
                //ShowMessage("混流功能不可使用，请在TRTCGetUserIDAndUserSig.h->TXCloudAccountInfo填写混流的账号信息\n");
                return;
            }
            TRTCTranscodingConfig config = new TRTCTranscodingConfig();
            config.mode = TRTCTranscodingConfigMode.TRTCTranscodingConfigMode_Manual;
            config.appId = (uint)appId;
            config.bizId = (uint)bizId;
            config.videoWidth = (uint)this.Width;
            //config.videoWidth = 1200;
            config.videoHeight = (uint)this.Height;
            //config.videoHeight = 600;
            config.videoBitrate = 1200;
            config.videoFramerate = 15;
            config.videoGOP = 1;
            config.audioSampleRate = 48000;
            config.audioBitrate = 64;
            config.audioChannels = 1;
            config.mixUsersArraySize = (uint)(locations.Count + 1);
            TRTCMixUser[] mixUsersArray = null;

            int zorder = 2;
            int index = 1;
            var shareVideo = locations.FirstOrDefault(l => l.Item5.StartsWith("share***"));
            if (shareVideo != null)
            {
                config.mixUsersArraySize = 2;
                mixUsersArray = new TRTCMixUser[2];
                var cuser = new TRTCMixUser();
                cuser.userId = this.name;
                cuser.zOrder = 2;
                cuser.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeBig;
                RECT crect = new RECT()
                {
                    left = this.Width - 200,
                    top = this.Height - 100,
                    right = this.Width,
                    bottom = this.Height,
                };
                cuser.rect = crect;
                mixUsersArray[0] = cuser;

                var shareuser = new TRTCMixUser();
                shareuser.userId = this.name;
                shareuser.zOrder = 1;
                shareuser.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeSub;
                RECT sharerect = new RECT()
                {
                    left = 0,
                    top = 0,
                    right = this.Width,
                    bottom = this.Height,
                };
                shareuser.rect = sharerect;
                mixUsersArray[1] = shareuser;
                config.mixUsersArray = mixUsersArray;
                mTRTCCloud.setMixTranscodingConfig(config);
                return;
            }
            else
            {
                config.mixUsersArraySize = (uint)locations.Count;
                mixUsersArray = new TRTCMixUser[config.mixUsersArraySize];
                var currentVideo = locations.FirstOrDefault(l => l.Item5 == this.name);
                if (currentVideo != null)
                {
                    var cuser = new TRTCMixUser();
                    cuser.userId = this.name;
                    cuser.zOrder = 1;
                    cuser.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeBig;
                    RECT crect = new RECT();
                    if (locations.Count == 1)
                    {
                        crect.left = 0;
                        crect.top = 0;
                        crect.right = this.Width;
                        crect.bottom = this.Height;
                    }
                    else
                    {
                        crect.left = currentVideo.Item1;
                        crect.top = currentVideo.Item2;
                        crect.right = currentVideo.Item3;
                        crect.bottom = currentVideo.Item4;
                    }
                    cuser.rect = crect;
                    mixUsersArray[0] = cuser;
                    locations.Remove(currentVideo);
                }
                else
                {
                    config.mixUsersArraySize = 2;
                    mixUsersArray = new TRTCMixUser[config.mixUsersArraySize];
                    var focuseUser = locations[0];
                    var fuser = new TRTCMixUser();
                    fuser.userId = focuseUser.Item5;
                    fuser.zOrder = 1;
                    fuser.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeBig;
                    RECT frect = new RECT();
                    if (locations.Count == 1)
                    {
                        frect.left = 0;
                        frect.top = 0;
                        frect.right = this.Width;
                        frect.bottom = this.Height;
                    }
                    else
                    {
                        frect.left = focuseUser.Item1;
                        frect.top = focuseUser.Item2;
                        frect.right = focuseUser.Item3;
                        frect.bottom = focuseUser.Item4;
                    }

                    fuser.rect = frect;
                    mixUsersArray[0] = fuser;

                    var cuser = new TRTCMixUser();
                    cuser.userId = this.name;
                    cuser.zOrder = 2;
                    cuser.pureAudio = true;
                    cuser.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeBig;
                    RECT crect = new RECT()
                    {
                        left = 0,
                        top = 0,
                        right = this.Width,
                        bottom = this.Height,
                    };
                    cuser.rect = crect;
                    mixUsersArray[1] = cuser;
                    locations.Remove(focuseUser);
                }
            }

            for (int i = 0; i < locations.Count; i++)
            {
                var user = new TRTCMixUser();

                string userName = locations[i].Item5;
                if (locations[i].Item5.StartsWith("share***"))
                {
                    userName = locations[i].Item5.Substring(8);
                    user.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeSub;
                    //user.roomId = null;
                }
                else
                {
                    //user.roomId = roomId.ToString();
                    user.streamType = TRTCVideoStreamType.TRTCVideoStreamTypeBig;
                }

                if (locations[i].Item4 == 1)
                {
                    user.pureAudio = true;
                }

                user.userId = userName;
                user.zOrder = zorder;
                RECT rect = new RECT()
                {
                    left = locations[i].Item1,
                    top = locations[i].Item2,
                    right = locations[i].Item3,
                    bottom = locations[i].Item4,
                    //right = 100,
                    //bottom = 100,
                };

                user.rect = rect;
                mixUsersArray[index] = user;
                zorder++;
                index++;
            }

            config.mixUsersArray = mixUsersArray;
            mTRTCCloud.setMixTranscodingConfig(config);
        }

        private void RemoveVideoMeta(string userId, TRTCVideoStreamType streamType)
        {
            foreach (UserVideoMeta info in mMixStreamVideoMeta)
            {
                if (info.userId == userId && info.streamType == streamType)
                {
                    mMixStreamVideoMeta.Remove(info);
                    break;
                }
            }
        }

        private int FindOccupyRemoteVideoPosition(string userId, bool isExitRoom)
        {
            return 1;
        }

        private void SetVisableInfoView(int pos, bool visable)
        {
        }

        private int GetIdleRemoteVideoPosition(String userId)
        {
            return 1;
        }

        private void SendRaiseHandMsg()
        {
            var data = Encoding.UTF8.GetBytes("raise");
            mTRTCCloud.sendCustomCmdMsg(MessageId.RaiseHand, data, (uint)data.Length, true, true);
        }

        private void SendDownHandMsg()
        {
            var data = Encoding.UTF8.GetBytes("down");
            mTRTCCloud.sendCustomCmdMsg(MessageId.DownHand, data, (uint)data.Length, true, true);
        }
        private void OnFormLoad(object sender, EventArgs e)
        {
            videoContainer.InitVideoContainer(this.fullScreenButton);
            videoContainer.NormalScreenUserChanged += VideoContainer_NormalScreenUserChanged;
            userList.RemoveUserClicked += UserList_RemoveUserClicked;
            if (!isPhilipMode)
            {
                lianjieServer();
            }
            TCommon.AppContext.VirtualCamera = new VirtualCamera.VirtualCamera();
            mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
            TCommon.AppContext.MessageBoard = new MessageBoardForm(this.Location, this.Width, this.Height);
            // 设定按字体来缩放控件
            //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            //设定字体大小为12px     
            // this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
            //string userSig = GenerateTestUserSig.GetInstance().GenTestUserSig(this.name);
            TRTCParams trtcParams = new TRTCParams();
            trtcParams.sdkAppId = GenerateTestUserSig.SDKAPPID;
            trtcParams.roomId = (uint)this.roomId;
            trtcParams.userId = this.name;
            trtcParams.userSig = this.UserSign;
            if (PropertySaver.GetInstance().appScene == TRTCAppScene.TRTCAppSceneLIVE) {
                trtcParams.role = currentRole;
            }
            roomId1 = this.roomId;
            name1 = this.name;
            raiseCount1.Hide();
            this.Hide();
            //var websocket = new WebSocketHelper();
            //SaveUserInfo();
            //this.SetTestEnv(0);
            //if (mTRTCCloud != null)
            //{
            //    mTRTCCloud.enterRoom(ref trtcParams, TRTCAppScene.TRTCAppSceneLIVE);
            //}
            
            this.EnterRoom(trtcParams);
            // }
        }

        private void UserList_RemoveUserClicked(string userid)
        {
            this.RemoveUserClicked?.Invoke(userid, ServiceId);
        }

        private void VideoContainer_NormalScreenUserChanged(string userId, bool isAdd)
        {
            userList.SetUserNameColor(userId, isAdd);
        }

        private void VideoMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ShowClosePrompt)
            {
                string message = string.Empty;
                if (role == UserRole.Host)
                {
                    message = "是否退出咨询？";
                }
                else
                {
                    message = "是否退出咨询？";
                }
                var result = System.Windows.MessageBox.Show(message, "确认退出", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {                
                    Uninit();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else {
                Uninit();
            }
        }

        private void clear()
        {
            isscene1 = "";
            topupmai = false;
            Focuse = "";
        }

        private void handButton_CheckStatusChanged(bool isChecked)
        {
            if (isChecked)
            {
                string inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":1{3}", "{", TRTC.VideoMainForm.roomId1, name, "}");
                TRTC.VideoMainForm.fasongmessage(inputMsg);
                SendRaiseHandMsg();
                userList.UpdateHandStatus(this.name, true);
            }
            else
            {
                string inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":2{3}", "{", TRTC.VideoMainForm.roomId1, name, "}");
                TRTC.VideoMainForm.fasongmessage(inputMsg);
                SendDownHandMsg();
                userList.UpdateHandStatus(this.name, false);
            }
        }

        private void cameraButton_CheckStatusChanged(bool isChecked)
        {
            if (!mIsEnterSuccess)
            {
                ShowMessage("进房失败，请重试");
                this.cameraButton.IsChecked = false;
                return;
            }
            if (this.cameraButton.IsChecked)
            {
                // 开启本地视频画面
                mTRTCCloud.muteLocalVideo(false);
                userList.UpdateVideoStatus(this.name, true);
                // 视频出现白边，重新加载
                mTRTCCloud.startLocalPreview(mCameraLocalVideo);
                if (this.shareButton.IsChecked)
                {
                    mTRTCCloud.resumeScreenCapture();
                }
                videoContainer.UpdateVideoUserCameraStatus(name, false);
            }
            else
            {
                mTRTCCloud.muteLocalVideo(true);
                userList.UpdateVideoStatus(this.name, false);
                // 视频出现白边，重新加载
                mTRTCCloud.stopLocalPreview();
                if (this.shareButton.IsChecked)
                {
                    mTRTCCloud.pauseScreenCapture();
                }
                videoContainer.UpdateVideoUserCameraStatus(name, true);
            }
        }

        private void shareButton1_CheckStatusChanged(bool isChecked)
        {
            if (!mIsEnterSuccess)
            {
                ShowMessage("进房失败，请重试");
                this.shareButton.IsChecked = false;
                return;
            }

            if ((isscene1 == "1" && !TCommon.AppContext.IsOnMic) ||
                (!TCommon.AppContext.isHost && TCommon.AppContext.FocusedUser != this.name && userList.Count > 4
                && !TCommon.AppContext.IsOnMic))
            {
                if (this.shareButton.IsChecked)
                    this.shareButton.IsChecked = false;
                return;
            }

            ITRTCDeviceCollection cameraList = mTRTCCloud.getCameraDevicesList();
            if (this.shareButton.IsChecked)
            {
                // 开启屏幕分享功能
                for (uint i = 0; i < cameraList.getCount(); i++)
                {
                    if (cameraList.getDeviceName(i).Equals(AppConst.VirtualCameraName))
                    {
                        if (mSettingForm == null)
                        {
                            mSettingForm = new TRTCSettingForm(mTRTCCloud, this);
                        }
                        mSettingForm.SetCameraHighResolution();
                        TCommon.AppContext.VirtualCamera.StartCaptureScreen();
                        //mTRTCCloud.startSystemAudioLoopback("");
                        //mTRTCCloud.setSystemAudioLoopbackVolume(80);

                        mTRTCCloud.setCurrentCameraDevice(cameraList.getDevicePID(i));
                        OnCameraDeviceChange(cameraList.getDeviceName(i));
                        mCurCameraDevice = cameraList.getDeviceName(i);
                        //MeetingConfig.GetInstance().CameraName = cameraList.getDeviceName(i);
                        //MeetingConfig.GetInstance().SaveConfig();
                        // 显示“停止共享”按钮
                        if (mStopSharingDesktopForm != null && !mStopSharingDesktopForm.IsDisposed)
                            mStopSharingDesktopForm.Show();
                        return;
                    }
                }
            }
            else
            {
                TCommon.AppContext.isSharingScreen = false;

                for (uint i = 0; i < cameraList.getCount(); i++)
                {
                    if (!cameraList.getDeviceName(i).Equals(AppConst.VirtualCameraName))
                    {
                        if (mSettingForm == null)
                        {
                            mSettingForm = new TRTCSettingForm(mTRTCCloud, this);
                        }
                        mSettingForm.SetCameraNormalResolution();
                        TCommon.AppContext.VirtualCamera.StopCaptureScreen();

                        mTRTCCloud.setCurrentCameraDevice(cameraList.getDevicePID(i));
                        OnCameraDeviceChange(cameraList.getDeviceName(i));
                        mCurCameraDevice = cameraList.getDeviceName(i);
                        // 隐藏“停止分享”按钮
                        // 显示“停止共享”按钮
                        mStopSharingDesktopForm.Hide();
                        return;
                    }
                }
            }
        }

        //布局
        private void layoutButton1_BtnClicked()
        {
            videoContainer.ToggleLayout();
        }

        private void quitButton1_BtnClicked()
        {
            this.Close();
        }

        public void OnCameraDeviceChange(string deviceName)
        {
            mCurCameraDevice = deviceName;
        }

        public void OnMicDeviceChange(string deviceName)
        {
            mCurMicDevice = deviceName;
        }

        public void OnSpeakerDeviceChange(string deviceName)
        {
            mCurSpeakerDevice = deviceName;
        }

        private void arrowAudioButton_BtnClicked()
        {
            var currentMic = mTRTCCloud.getCurrentMicDevice();
            var micList = mTRTCCloud.getMicDevicesList();

            var currentSpeaker = mTRTCCloud.getCurrentSpeakerDevice();
            var speakerList = mTRTCCloud.getSpeakerDevicesList();

            var audioMenu = new ContextMenuStrip();
            audioMenu.BackColor = Color.White;
            audioMenu.ItemClicked += AudioMenu_ItemClicked;
            var cameraImage = Image.FromHbitmap(Resources.audio_mute.GetHbitmap());
            var cameraTitleItem = new ToolStripMenuItem("选择麦克风", cameraImage);
            cameraTitleItem.Enabled = false;
            audioMenu.Items.Add(cameraTitleItem);

            for (uint i = 0; i < micList.getCount(); i++)
            {
                if (currentMic.getDeviceName() == micList.getDeviceName(i))
                {
                    var selectedImage = Image.FromHbitmap(Resources.selected.GetHbitmap());
                    var micItem = new ToolStripMenuItem(micList.getDeviceName(i), selectedImage);
                    audioMenu.Items.Add(micItem);
                }
                else
                {
                    var micItem = new ToolStripMenuItem(micList.getDeviceName(i));
                    audioMenu.Items.Add(micItem);
                }
            }

            var microImage = Image.FromHbitmap(Resources.audio_mute.GetHbitmap());
            var microTitleItem = new ToolStripMenuItem("选择扬声器", microImage);
            microTitleItem.Enabled = false;

            audioMenu.Items.Add(microTitleItem);
            for (uint i = 0; i < speakerList.getCount(); i++)
            {
                if (currentSpeaker.getDeviceName() == speakerList.getDeviceName(i))
                {
                    var selectedImage = Image.FromHbitmap(Resources.selected.GetHbitmap());
                    var micItem = new ToolStripMenuItem(speakerList.getDeviceName(i), selectedImage);
                    micItem.Tag = 1;
                    audioMenu.Items.Add(micItem);
                }
                else
                {
                    var micItem = new ToolStripMenuItem(speakerList.getDeviceName(i));
                    micItem.Tag = 1;
                    audioMenu.Items.Add(micItem);
                }
            }

            var settingImage = Image.FromHbitmap(Resources.settings.GetHbitmap());
            var settingTitleItem = new ToolStripMenuItem("设置", settingImage);
            audioMenu.Items.Add(settingTitleItem);
            var y = 23 * audioMenu.Items.Count;
            var position = new System.Drawing.Point(-110, -y);
            audioMenu.Show(arrowVideoButton, position);
            micList.release();
            speakerList.release();
        }

        private void AudioMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            var micList = mTRTCCloud.getMicDevicesList();
            var speakerList = mTRTCCloud.getSpeakerDevicesList();
            var name = e.ClickedItem.Text;

            bool isSpeak = e.ClickedItem.Tag == null ? false : (int)e.ClickedItem.Tag == 1;

            if (!isSpeak)
            {
                for (uint i = 0; i < micList.getCount(); i++)
                {
                    if (micList.getDeviceName(i).Equals(name))
                    {
                        mTRTCCloud.setCurrentMicDevice(micList.getDevicePID(i));
                        OnMicDeviceChange(micList.getDeviceName(i));
                        MeetingConfig.GetInstance().MicroName = micList.getDeviceName(i);
                        MeetingConfig.GetInstance().SaveConfig();
                        return;
                    }
                }
            }
            else
            {

                for (uint i = 0; i < speakerList.getCount(); i++)
                {
                    if (speakerList.getDeviceName(i).Equals(name))
                    {
                        mTRTCCloud.setCurrentSpeakerDevice(speakerList.getDevicePID(i));
                        OnSpeakerDeviceChange(speakerList.getDeviceName(i));
                        MeetingConfig.GetInstance().SpeakerName = speakerList.getDeviceName(i);
                        MeetingConfig.GetInstance().SaveConfig();
                        return;
                    }
                }
            }

            if (name == "设置")
            {
                ispicclick = "音频设置";
                if (mDeviceForm == null)
                    mDeviceForm = new TRTCDeviceForm(mTRTCCloud, this);
                mDeviceForm.show(this);
                mDeviceForm.ShowDialog();

            }
        }

        private void arrowVideoButton_BtnClicked()
        {
            var currentCamera = mTRTCCloud.getCurrentCameraDevice();
            var cameraList = mTRTCCloud.getCameraDevicesList();

            var videoMenu = new ContextMenuStrip();
            videoMenu.BackColor = Color.White;
            videoMenu.ItemClicked += VideoMenu_ItemClicked;
            var cameraImage = Image.FromHbitmap(Resources.video_camera.GetHbitmap());
            var cameraTitleItem = new ToolStripMenuItem("选择摄像头", cameraImage);
            cameraTitleItem.Enabled = false;
            videoMenu.Items.Add(cameraTitleItem);

            for (uint i = 0; i < cameraList.getCount(); i++)
            {
                if (currentCamera.getDeviceName() == cameraList.getDeviceName(i))
                {
                    var selectedImage = Image.FromHbitmap(Resources.selected.GetHbitmap());
                    var micItem = new ToolStripMenuItem(cameraList.getDeviceName(i), selectedImage);
                    videoMenu.Items.Add(micItem);
                }
                else
                {
                    var micItem = new ToolStripMenuItem(cameraList.getDeviceName(i));
                    videoMenu.Items.Add(micItem);
                }
            }

            var settingImage = Image.FromHbitmap(Resources.settings.GetHbitmap());
            var settingTitleItem = new ToolStripMenuItem("设置", settingImage);
            videoMenu.Items.Add(settingTitleItem);
            var y = 24 * videoMenu.Items.Count;
            var position = new System.Drawing.Point(0, -y);
            videoMenu.Show(arrowVideoButton, position);
            cameraList.release();
        }
        public string ispicclick = "";
        private void VideoMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            var cameraList = mTRTCCloud.getCameraDevicesList();
            var name = e.ClickedItem.Text;

            for (uint i = 0; i < cameraList.getCount(); i++)
            {
                if (cameraList.getDeviceName(i).Equals(name))
                {
                    if (name.Equals(AppConst.VirtualCameraName))
                    {
                        if (mSettingForm == null)
                        {
                            mSettingForm = new TRTCSettingForm(mTRTCCloud, this);
                        }
                        mSettingForm.SetCameraHighResolution();
                        TCommon.AppContext.VirtualCamera.StartCaptureScreen();
                        mTRTCCloud.startSystemAudioLoopback("");
                        mTRTCCloud.setSystemAudioLoopbackVolume(80);
                    }
                    else
                    {
                        if (mSettingForm == null)
                        {
                            mSettingForm = new TRTCSettingForm(mTRTCCloud, this);
                        }
                        mSettingForm.SetCameraNormalResolution();
                        if (TCommon.AppContext.VirtualCamera != null)
                        {
                            TCommon.AppContext.VirtualCamera.StopCaptureScreen();
                            mTRTCCloud.stopSystemAudioLoopback();
                        }
                    }
                    mTRTCCloud.setCurrentCameraDevice(cameraList.getDevicePID(i));
                    OnCameraDeviceChange(cameraList.getDeviceName(i));
                    MeetingConfig.GetInstance().CameraName = cameraList.getDeviceName(i);
                    MeetingConfig.GetInstance().SaveConfig();
                    return;
                }
            }

            if (name == "设置")
            {
                ispicclick = "视频设置";
                if (mDeviceForm == null)
                    mDeviceForm = new TRTCDeviceForm(mTRTCCloud, this);
                mDeviceForm.show(this);
                mDeviceForm.ShowDialog();

            }
        }

        private void settingButton_BtnClicked()
        {
            if (mSettingForm == null)
            {
                mSettingForm = new TRTCSettingForm(mTRTCCloud, this);
            }
            mSettingForm.ShowDialog();
        }

        private void closeMeetingButton_BtnClicked()
        {
            var result = System.Windows.MessageBox.Show("是否确认结束本场会议？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                Uninit();
                ShowClosePrompt = false;
                this.Close();
                this.loginWindow11?.Show();
            }
        }

        private void dwonAllHandButton_BtnClicked()
        {
            var action = new ActionEntity()
            {
                ActionId = HostAction.DownAllHand
            };
            var actionString = JsonConvert.SerializeObject(action);
            var data = Encoding.UTF8.GetBytes(actionString);
            mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
            string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":108{2}", "{", roomId, "}");
            fasongmessage(inputMsg);
            if (isscene1 == "2") {
                userList.DownAllHand();
            }
        }

        private void stopShareButton_CheckStatusChanged(bool isChecked)
        {
            byte[] data;
            if (stopShareButton.IsChecked == false)
            {
                var action = new ActionEntity()
                {
                    ActionId = HostAction.StopShare
                };
                var actionString = JsonConvert.SerializeObject(action);
                data = Encoding.UTF8.GetBytes(actionString);
                mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
            }
            else
            {
                var action = new ActionEntity()
                {
                    ActionId = HostAction.AllowShare
                };
                var actionString = JsonConvert.SerializeObject(action);
                data = Encoding.UTF8.GetBytes(actionString);
                mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
            }
        }

        private void muteAllButton_CheckStatusChanged(bool isChecked)
        {
            byte[] data;
            if (muteAllButton.IsChecked == false)
            {
                var action = new ActionEntity()
                {
                    ActionId = HostAction.MuteAll
                };
                var actionString = JsonConvert.SerializeObject(action);
                data = Encoding.UTF8.GetBytes(actionString);
                mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":104{2}", "{", roomId, "}");
                fasongmessage(inputMsg);
            }
            else
            {
                var action = new ActionEntity()
                {
                    ActionId = HostAction.UnMuteAll
                };
                var actionString = JsonConvert.SerializeObject(action);
                data = Encoding.UTF8.GetBytes(actionString);
                mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":105{2}", "{", roomId, "}");
                fasongmessage(inputMsg);
            }
        }
        private bool HostMeetingLive(int roomId)
        {
            bool isSuccess = false;
            try
            {
                var urlFormat = "https://www.1meeting.cn/hostmeeting?roomid={0}&scene={1}";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(urlFormat, roomId, 1));
                var param = new object()
                {

                };
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, param);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                string dataString = Encoding.UTF8.GetString(dataBytes);
                stream.Close();
                request.Method = "POST";
                request.ContentType = "application/json";

                var requestByte = Encoding.UTF8.GetBytes(dataString);
                request.ContentLength = requestByte.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(requestByte, 0, requestByte.Length);
                    var response = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    var returnString = sr.ReadToEnd();
                    var responseStream = new MemoryStream(Encoding.UTF8.GetBytes(returnString));
                    DataContractJsonSerializer seri = new DataContractJsonSerializer(typeof(HostMeetingResponse));
                    var res = (HostMeetingResponse)seri.ReadObject(responseStream);
                    if (res != null)
                    {
                        //Time = 1;
                        Time = res.Time;
                        startTime = DateTime.Now;
                        Count = res.Count;
                    }

                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("主持会议接口调用失败");
            }

            return isSuccess;
        }
        private bool HostMeeting(int roomId)
        {
            bool isSuccess = false;
            try
            {
                var urlFormat = "https://www.1meeting.cn/hostmeeting?roomid={0}&scene={1}";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(urlFormat, roomId, 0));
                var param = new object()
                {

                };
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, param);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                string dataString = Encoding.UTF8.GetString(dataBytes);
                stream.Close();
                request.Method = "POST";
                request.ContentType = "application/json";

                var requestByte = Encoding.UTF8.GetBytes(dataString);
                request.ContentLength = requestByte.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(requestByte, 0, requestByte.Length);
                    var response = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    var returnString = sr.ReadToEnd();
                    var responseStream = new MemoryStream(Encoding.UTF8.GetBytes(returnString));
                    DataContractJsonSerializer seri = new DataContractJsonSerializer(typeof(HostMeetingResponse));
                    var res = (HostMeetingResponse)seri.ReadObject(responseStream);
                    if (res != null)
                    {
                        //Time = 1;
                        Time = res.Time;
                        startTime = DateTime.Now;
                        Count = res.Count;
                    }

                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("主持会议接口调用失败");
            }

            return isSuccess;
        }

        private bool TerminateMeeting(int roomId)
        {
            bool isSuccess = false;
            try
            {
                var urlFormat = "https://www.1meeting.cn/checkwxmeeting?roomid={0}";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(urlFormat, roomId));
                var param = new object()
                {

                };
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, param);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                string dataString = Encoding.UTF8.GetString(dataBytes);
                stream.Close();
                request.Method = "POST";
                request.ContentType = "application/json";

                var requestByte = Encoding.UTF8.GetBytes(dataString);
                request.ContentLength = requestByte.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(requestByte, 0, requestByte.Length);
                    var response = (HttpWebResponse)request.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    var returnString = sr.ReadToEnd();
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("主持人结束会议接口调用失败");
            }

            return isSuccess;
        }

        private void usersButton_BtnClicked()
        {
            userList.Visible = !userList.Visible;
            videoContainer.userlist(userList);
            if (chatControl.Visible)
            {
                chatControl.Visible = false;
            }

            if (userList.Visible)
            {
                userList.BringToFront();
                TCommon.AppContext.MessageBoard.Width = TCommon.AppContext.MessageBoard.Width - userList.Width;
            }
            else {
                TCommon.AppContext.MessageBoard.Width = TCommon.AppContext.MessageBoard.Width + userList.Width;
            }
        }

        private void nextBtn_Click(object sender, EventArgs e)
        {
            videoContainer.NormalNextPage();
        }

        private void preBtn_Click(object sender, EventArgs e)
        {
            videoContainer.NormalPrePage();
        }

        private void smallPreBtn_Click(object sender, EventArgs e)
        {
            videoContainer.FocusePrePage();
        }

        private void smallNextBtn_Click(object sender, EventArgs e)
        {
            videoContainer.FocuseNextPage();
        }

        private void shareLiveButton_BtnClicked()
        {
            // 计算 CDN 地址(格式： http://[bizid].liveplay.myqcloud.com/live/[bizid]_[streamid].flv )
            int bizId = GenerateTestUserSig.BIZID;
            // streamid = MD5 (房间号_用户名_流类型)
            var array = name.Split(new string[] { "$$$" }, StringSplitOptions.None);
            string streamId = Util.MD5(String.Format("{0}_{1}_{2}", mRoomId, Util.UTF16To8(array[0]), "main"));
            string shareUrl = String.Format("http://{0}.liveplay.myqcloud.com/live/{0}_{1}.flv", bizId, streamId);
            //Log.I("播放地址： " + shareUrl);
            System.Windows.Clipboard.SetDataObject(shareUrl);
            ShowMessage("播放地址：（已复制到剪切板）\n" + shareUrl);
        }

        private void livesButton1_CheckStatusChanged(bool isChecked)
        {
            if (!mIsEnterSuccess)
            {
                ShowMessage("进房失败，请重试");
                this.livesButton1.IsChecked = false;
                return;
            }
            if (this.livesButton1.IsChecked)
            {
                var array = name.Split(new string[] { "$$$" }, StringSplitOptions.None);
                // 开启云端画面混合功能
                UpdateMixTranCodeInfo();
                var param = new TRTCPublishCDNParam()
                {
                    appId = GenerateTestUserSig.APPID,
                    bizId = GenerateTestUserSig.BIZID,
                    //url = "rtmp://livepush.tcloud.com/live/" + array[0]
                    url = TCommon.AppContext.PushUrl
                };
                mTRTCCloud.startPublishCDNStream(ref param);
                //shareLiveButton.Visible = true;
            }
            else
            {
                // 关闭与那段画面混合功能
                mTRTCCloud.setMixTranscodingConfig(null);
                mTRTCCloud.stopPublishCDNStream();
                //shareLiveButton.Visible = false;
            }
        }

        private void VideoMainForm_Activated(object sender, EventArgs e)
        {
            videoContainer.ActivateForm();
            //TCommon.AppContext.MessageBoard.Show();
        }

        private void openAllVideo_BtnClicked()
        {
            var action = new ActionEntity()
            {
                ActionId = HostAction.OpenAllVideo
            };
            var actionString = JsonConvert.SerializeObject(action);
            var data = Encoding.UTF8.GetBytes(actionString);
            mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
        }

        private void closeAllVideo_BtnClicked()
        {
            var action = new ActionEntity()
            {
                ActionId = HostAction.CloseAllVideo
            };
            var actionString = JsonConvert.SerializeObject(action);
            var data = Encoding.UTF8.GetBytes(actionString);
            mTRTCCloud.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
        }

        private void chatButton1_BtnClicked()
        {
            MsgSend msgSend = new MsgSend(this);
            msgSend.ShowDialog();
        }
        public static int roomId1;
        public static string name1;
        // 这里的URL配置成你websocket服务端的地址就好了
        // wss://talk.1meeting.com:9501
        //wss://47.96.94.140:9501
        private static string url = "wss://talk.1meeting.com:9501";
        public static WSocketClient client = null;

        public static void SetCertificatePolicy()
        {
            ServicePointManager.ServerCertificateValidationCallback
                       += RemoteCertificateValidate;
            // ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        }

        /// <summary>
        /// Remotes the certificate validate.
        /// </summary>
        private static bool RemoteCertificateValidate(
           object sender, X509Certificate cert,
            X509Chain chain, SslPolicyErrors error)
        {
            // trust any certificate!!!
            System.Console.WriteLine("Warning, trust any certificate");
            return true;
        }
        private void lianjieServer()
        {
            SetCertificatePolicy();
            //新建客户端类 
            //服务端IP地址 ws://47.96.94.140 如果服务端开启了ssl或者tsl 这里前缀应该改成 wss:/
            //服务端监听端口 9501
            //自定义的地址参数 可以根据地址参数来区分客户端 /lcj控制台
            //开始链接
            try
            {
                client = new WSocketClient(url);
                client.MessageReceived += MessageReceived;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
            }
        }
        public static void fasongmessage(string msg)
        {
            try
            {
                // System.Windows.MessageBox.Show(msg);
                if (string.IsNullOrEmpty(msg))
                    System.Windows.MessageBox.Show("空值不让传！");
                client?.SendMessage(msg);
                // System.Windows.MessageBox.Show("发送成功");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 服务端返回的消息
        /// </summary>
        private void MessageReceived(string data)
        {
            try
            {
                //注册消息接收事件，接收服务端发送的数据
                
                JObject jo = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(data);
                if (jo["cmd"] != null && jo["roomid"].ToString() == roomId.ToString())
                {
                    int cmdId = int.Parse(jo["cmd"].ToString());
                    switch (jo["cmd"].ToString())
                    {
                        // 参会者举手
                        case "1":                       
                                if (jo["userid"] != null)
                                {
                                    this.Invoke((Action)delegate ()
                                    {
                                        userList.UpdateHandStatus(jo["userid"].ToString(), true);
                                    });
                                }
                            break;
                        //参会者放下举手
                        case "2":
                                if (jo["userid"] != null)
                                {
                                    this.Invoke((Action)delegate ()
                                    {
                                        userList.UpdateHandStatus(jo["userid"].ToString(), false);
                                    });
                                }
                            break;
                        //主持人关闭某个参会者麦克风  
                        //case "111":
                        //    if (jo["userid"].ToString() == userName)
                        //    {
                        //        item.receivemsg("静音");
                        //        UpdateAudioStatus(jo["userid"].ToString(), false);
                        //    }
                        //    break;
                        //主持人开启某个参会者麦克风  
                        //case "112":
                        //    if (jo["userid"].ToString() == userName)
                        //    {
                        //        item.receivemsg("取消静音");
                        //        UpdateAudioStatus(jo["userid"].ToString(), true);
                        //    }
                        //    break;
                        ////.主持人关闭某个参会者摄像头
                        //case "115":
                        //    if (jo["userid"].ToString() == userName)
                        //    {
                        //        if (this.IsHandleCreated)
                        //        {
                        //            this.Invoke((Action)delegate ()
                        //            {
                        //                item.receivemsg("关闭视频");
                        //                UpdateVideoStatus(jo["userid"].ToString(), false);
                        //            });
                        //        }
                        //    }
                        //    break;
                        ////.主持人打开某个参会者摄像头
                        //case "116":

                        //    if (jo["userid"].ToString() == userName)
                        //    {
                        //        if (this.IsHandleCreated)
                        //        {
                        //            this.Invoke((Action)delegate ()
                        //            {
                        //                item.receivemsg("打开视频");
                        //                UpdateVideoStatus(jo["userid"].ToString(), true);
                        //            });
                        //        }
                        //    }
                        //    break;
                        //主持人将会议间任一参会者或自己放在第一位
                        //case "113":
                        //    if (jo["userid"].ToString() == userName)
                        //    {
                        //        this.Invoke((Action)delegate ()
                        //        {
                        //            item.receivemsg("设为焦点");
                        //            // UpdateVideoStatus(jo["userid"].ToString(), true);
                        //        });
                        //    }
                        //    break;
                        case "11":
                            if (TCommon.AppContext.startFromOldVersion) {
                                userList.RemoveUer(jo["userid"].ToString());
                            }
                            foreach (string user in mRoomUsers)
                            {
                                if (user.Equals(jo["userid"].ToString()))
                                {
                                    mRoomUsers.Remove(user);
                                    userList.RemoveUer(user);
                                    break;
                                }
                            }
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    if (videoContainer.IsDisposed==true)
                                    {

                                    }
                                    else
                                    {
                                        videoContainer.RemoveUser(jo["userid"].ToString());
                                    }

                                });
                            }
                            int pos = FindOccupyRemoteVideoPosition(jo["userid"].ToString(), true);
                                    if (pos != -1)
                                    {
                                        if (mTRTCCloud != null)
                                        {
                                            mTRTCCloud.stopRemoteView(jo["userid"].ToString());
                                            mTRTCCloud.stopRemoteSubStreamView(jo["userid"].ToString());
                                        }
                                    }
                            
                            break;
                        case "10":
                            if (jo["userid"].ToString() == this.name)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    userList.AddUser(jo["userid"].ToString());
                                    if (!mRoomUsers.Contains(jo["userid"].ToString()))
                                        mRoomUsers.Add(jo["userid"].ToString());
                                });
                                return;
                            }
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    userList.AddUser(jo["userid"].ToString());
                                    if (!mRoomUsers.Contains(jo["userid"].ToString()))
                                        mRoomUsers.Add(jo["userid"].ToString());
                                });
                            }
                            if (TCommon.AppContext.isHost)
                            {
                                if (!TCommon.AppContext.AllowChat)
                                {
                                    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2}{3}", "{", TRTC.VideoMainForm.roomId1, 127, "}");
                                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                                }

                                if (!TCommon.AppContext.AllowOnMic) {
                                    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2}{3}", "{", TRTC.VideoMainForm.roomId1, 129, "}");
                                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                                }
                            }
                            string msg = string.Format("{0}\"roomid\":{1},\"cmd\":12,\"userid\":\"{2}\"{3}", "{",
                                TRTC.VideoMainForm.roomId1, name, "}");
                            fasongmessage(msg);
                            break;
                        //用户列表更新
                        case "12":
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    userList.AddUser(jo["userid"].ToString());
                                    if (!mRoomUsers.Contains(jo["userid"].ToString()))
                                        mRoomUsers.Add(jo["userid"].ToString());
                                });
                            }
                            break;
                        //移出会议
                        case "110":
                            //if (this.IsHandleCreated)
                            //{
                            //    this.Invoke((Action)delegate ()
                            //    {
                            //        if (TCommon.AppContext.isHost)
                            //        {
                            //        }
                            //        if (jo["userid"].ToString() == this.name) {
                            //            ShowClosePrompt = false;
                            //            this.Close();
                            //            System.Windows.MessageBox.Show("主持人将您移除了会议");
                            //        }                               
                            //    });
                            //}
                            break;
                        //主持人将参会者的举手放下
                        case "3":
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    if (jo["userid"].ToString() == name)
                                    {
                                        handButton.IsChecked = false;
                                    }
                                    userList.UpdateHandStatus(jo["userid"].ToString(), false);
                                });
                                
                            }
                            break;
                        //弹幕
                        case "9":
                            if (jo["roomid"].ToString() == roomId.ToString())
                            {
                                string name = StringUtil.UserNameFromHex(jo["userid"].ToString());
                                AddTanMu(name + "：" + jo["txt"].ToString());
                            }
                            break;
                        //主持人关闭房间内所有人弹幕功能
                        case "127":
                            if (TCommon.AppContext.isHost == false)
                            {
                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((Action)delegate ()
                                    {
                                        // chatButton1.Enabled = false;
                                        SetControlEnabled(this.chatButton1, false);
                                    });
                                }
                            }
                            break;
                        //主持人打开房间内所有人弹幕功能
                        case "128":
                            if (TCommon.AppContext.isHost == false)
                            {
                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((Action)delegate ()
                                    {
                                        //chatButton1.Enabled = true;
                                        SetControlEnabled(this.chatButton1, true);
                                    });
                                }
                            }
                            break;
                        //请求上麦
                        case "13":
                            if (VideoContainer.normalScreenUsers.Count <= 4)
                            {
                                if (TCommon.AppContext.isHost == true)
                                {
                                    if (jo["roomid"].ToString() == roomId.ToString())
                                    {
                                        if (!userOnRequest.Contains(jo["userid"].ToString()) && userOnRequest.Count <= 5)
                                        {
                                            userOnRequest.Add(jo["userid"].ToString());
                                            Task.Factory.StartNew(new Action(() =>
                                            {
                                                if (this.IsHandleCreated)
                                                {
                                                    this.Invoke((Action)delegate ()
                                                    {
                                                        string name = StringUtil.UserNameFromHex(jo["userid"].ToString());
                                                        DialogResult dr = System.Windows.Forms.MessageBox.Show("是否同意" + name + "的请求上麦", "请求上麦", MessageBoxButtons.YesNo);
                                                        if (dr == DialogResult.Yes)
                                                        {
                                                            string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\"{4}", "{", TRTC.VideoMainForm.roomId1, (int)WsMessageId.AgreeLianMai, jo["userid"].ToString(), "}");
                                                            fasongmessage(inputMsg);
                                                            topupmai = true;
                                                            userList.UpdateMicroOn(jo["userid"].ToString(), true);
                                                        }

                                                        userOnRequest.Remove(jo["userid"].ToString());
                                                    });
                                                }
                                            }));
                                        }
                                            
                                    }
                                }
                            }
                            break;
                        //请求下麦
                        case "14":
                            if (TCommon.AppContext.isHost == true)
                            {
                                if (jo["roomid"].ToString() == roomId.ToString())
                                {
                                    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\"{4}", "{", TRTC.VideoMainForm.roomId1, 125, jo["userid"].ToString(), "}");
                                    fasongmessage(inputMsg);
                                    topupmai = false;
                                    userList.UpdateMicroOn(jo["userid"].ToString(), false);
                                }
                            }
                            break;
                        //设置为主播角色（直播）（主持人）
                        case "126":
                            if (isscene1 == "1")
                            {
                                if (jo["roomid"].ToString() == roomId.ToString() &&
                                this.name == jo["userid"].ToString())
                                {
                                    if (this.IsHandleCreated)
                                    {
                                        this.Invoke((Action)delegate ()
                                        {
                                            TCommon.AppContext.IsOnMic = true;
                                            topupmai = true;
                                            microButton.Enabled = true;
                                            cameraButton.Enabled = true;
                                            shareButton.Enabled = true;
                                            layoutButton1.Enabled = true;
                                            handButton.Enabled = true;
                                            dwonAllHandButton.Enabled = true;
                                            livesButton1.Enabled = true;
                                            stopShareButton.Enabled = true;
                                            muteAllButton.Enabled = true;
                                            mCameraLocalVideo = videoContainer.GetVideoHandle(this.name);
                                            mTRTCCloud.switchRole(TRTCRoleType.TRTCRoleAnchor);
                                            mTRTCCloud.startLocalPreview(mCameraLocalVideo);
                                            mTRTCCloud.startLocalAudio();
                                            upanddownwheat1.IsChecked = true;
                                        });
                                    }
                                }
                            }
                            break;
                        //主持人放下全部举手
                        case "108":
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    handButton.IsChecked = false;
                                });
                            }                          
                            break;
                        //设置为观众角色（直播）（主持人）
                        case "125":
                            // System.Windows.Forms.MessageBox.Show(list.Count.ToString());
                            if (isscene1 == "1")

                                if (jo["roomid"].ToString() == roomId.ToString() &&
                                this.name == jo["userid"].ToString())
                                {
                                    if (this.IsHandleCreated)
                                    {
                                        this.Invoke((Action)delegate ()
                                        { 
                                            topupmai = false;
                                            mTRTCCloud.switchRole(TRTCRoleType.TRTCRoleAudience);
                                            mTRTCCloud.stopLocalPreview();
                                            mTRTCCloud.stopLocalAudio();
                                            this.shareButton.IsChecked = false;
                                            TCommon.AppContext.IsOnMic = false;
                                            videoContainer.RemoveUser(this.name);
                                            if (upanddownwheat1.IsChecked == true) {
                                                upanddownwheat1.IsChecked = false;
                                            }
                                        });
                                    }
                                    //  }
                                }
                            break;
                        //主持人关闭房间内所有人上麦功能
                        case "129":
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    if (jo["roomid"].ToString() == roomId.ToString())
                                    {
                                        SetControlEnabled(upanddownwheat1, false);
                                    }
                                });
                            }                           
                            break;
                        //主持人开启房间内所有人上麦功能
                        case "130":
                            if (this.IsHandleCreated)
                            {
                                this.Invoke((Action)delegate ()
                                {
                                    if (jo["roomid"].ToString() == roomId.ToString())
                                    {
                                        SetControlEnabled(upanddownwheat1, true);
                                    }
                                });
                            }                       
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        private void labRaiseHand_TextChanged(object sender, EventArgs e)
        {
            //if (labRaiseHand.Text == "0" || string.IsNullOrEmpty(labRaiseHand.Text))
            //{
            //    labRaiseHand.Text = "";
            //    pictureBox.Hide();
            //}
            //else
            //{
            //    pictureBox.Show();
            //}
        }

        private void pictureBox_Click(object sender, EventArgs e)
        {
            userList.Visible = !userList.Visible;

            if (chatControl.Visible)
            {
                chatControl.Visible = false;
            }

            if (userList.Visible)
            {
                userList.BringToFront();
            }
        }
        //画廊
        public static string Focuse = "";
        private void layoutButton1_BtnClicked_1()
        {
            var manager = new ServiceManager();
            var roomId = TCommon.AppContext.isHost ?
                TCommon.AppContext.LocalRoomId : TCommon.AppContext.AttendRoomId;
            var userId = manager.GetFocuseUser(roomId);
            if (!string.IsNullOrEmpty(userId))
            {
                videoContainer.SetFocuseUser(userId);
                userList.SetFocuseUser(userId);
                Focuse = userId;
            }
            //videoContainer.layout(this);
        }
        #region 发送弹幕
        List<Label> TanMuList = new List<Label>();
        //是否打开弹幕
        public void AddTanMu(String word)
        {
            try
            {
                //Label label = new Label();  
                //label.Text = word;
                //label.AutoSize = true;
                //label.ForeColor = Color.Red;
                //label.BackColor = Color.Transparent;
                ////label.BackColor = Color.FromArgb(50, Color.White);
                //label.Font = new Font("宋体", 17);
                //label.Location = new System.Drawing.Point(this.Width, new Random().Next(this.Height - label.Height));
                //label.BringToFront();
                //TanMuList.Add(label);
                if (this.IsHandleCreated)
                {
                    this.Invoke(new Action(() =>
                {
                    TCommon.AppContext.MessageBoard.ShowMsg(word, this.Location, this.Width, this.Height);
                }));
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
            }
        }
        private void timer1_Tick_1(object sender, EventArgs e)
        {
            TanMuList = TanMuList.Distinct().ToList();
            //只能使用for循环
            for (int i = 0; i < TanMuList.Count; i++)
            {
                Label label = TanMuList[i];
                label.BackColor = Color.FromArgb(127, 255,255,255); ;
                if (TRTCSettingForm.isopendanmu == false)
                {
                    label.Show();
                }
                else
                {
                    label.Hide();
                }

                //label.BringToFront();
                System.Drawing.Point point = label.Location;
                //步数、速度
                for (int v = 0; v < 15; v++)
                {
                    point.X = point.X - 1;
                    label.Location = point;
                }

                //超出移除
                if (point.X + label.Width < 0)
                {
                    label.Visible = false;
                    TanMuList.Remove(label);
                    videoContainer.Controls.Remove(label);
                }
            }

        }
        #endregion
        public void checkchat(bool istf)
        {
            if (istf == false)
            {
                chatButton1.Enabled = false;
            }
            else
            {
                chatButton1.Enabled = true;
            }

        }

        public void upDownmai(bool istruefalse)
        {
            if (istruefalse == true)
            {
                upanddownwheat1.Visible = false;
            }
            else
            {
                upanddownwheat1.Visible = true;
            }
        }

        private void VideoMainForm_SizeChanged(object sender, EventArgs e)
        {
            if (TCommon.AppContext.MessageBoard != null)
            {
                int width = this.Width;
                if (userList.Visible) {
                    width = this.Width - userList.Width;
                }
                TCommon.AppContext.MessageBoard.UpdateLS(this.Location, width, this.Height, this.Visible);
            }
        }

        private void VideoMainForm_LocationChanged(object sender, EventArgs e)
        {
            if (TCommon.AppContext.MessageBoard != null)
            {
                int width = this.Width;
                if (userList.Visible)
                {
                    width = this.Width - userList.Width;
                }
                TCommon.AppContext.MessageBoard.UpdateLS(this.Location, width, this.Height, this.Visible);
            }

            if (recordForm != null) {
                recordForm.Location = new System.Drawing.Point(this.Location.X + 15, 
                    this.Location.Y + this.Height - recordForm.Height - 65);
            }

            if (deviceForm != null)
            {
                deviceForm.Location = new System.Drawing.Point(this.Location.X + (int)(this.Width - deviceForm.Width) / 2,
                        this.Location.Y + (int)(this.Height - deviceForm.Height) / 2);
            }
        }

        private void VideoMainForm_Deactivate(object sender, EventArgs e)
        {
            //TCommon.AppContext.MessageBoard.Hide();
            //TCommon.AppContext.MessageBoard.TopMost = false;
        }

        private void upanddownwheat1_BtnClicked()
        {
            if (upanddownwheat1.IsChecked == false)
            {
                if (VideoContainer.normalScreenUsers.Count >= 4) {
                    System.Windows.MessageBox.Show("上麦人数已达上线，暂时无法请求上麦");
                    return;
                }

                DialogResult dr = System.Windows.Forms.MessageBox.Show("确定要请求上麦吗？", "提示", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.OK)//如果点击“确定”按钮
                {
                    string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\"{4}", "{", TRTC.VideoMainForm.roomId1, 13, name, "}");
                    fasongmessage(inputMsg);
                }
            }
            else
            {
                if (TCommon.AppContext.isSelfSharing) {
                    System.Windows.MessageBox.Show("请先停止共享后再下麦");
                    return;
                }
                string inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\"{4}", "{", TRTC.VideoMainForm.roomId1, 14, name, "}");
                fasongmessage(inputMsg);
            }
        }

        private void microButton_BtnClicked()
        {
            if (!mIsEnterSuccess)
            {
                ShowMessage("进房失败，请重试");
                this.microButton.IsChecked = false;
                return;
            }
            if (!this.microButton.IsChecked)
            {
                if (TCommon.AppContext.isMuted) {
                    System.Windows.MessageBox.Show("您已被主持人静音，需主持人解除静音才能开启语音");
                    return;
                }

                // 开启本地的音频
                mTRTCCloud.muteLocalAudio(false);
                userList.UpdateAudioStatus(this.name, true);
                this.microButton.IsChecked = true;
                cachMicroBtnStatus = true;
                videoContainer.UpdateVideoUserMicroStatus(name, false);
            }
            else
            {
                if (isscene1 == "1" && !TCommon.AppContext.IsOnMic)
                {
                    if (!this.microButton.IsChecked)
                        this.microButton.IsChecked = true;
                    return;
                }

                // 静音本地的音频
                mTRTCCloud.muteLocalAudio(true);
                userList.UpdateAudioStatus(this.name, false);
                this.microButton.IsChecked = false;
                cachMicroBtnStatus = false;
                videoContainer.UpdateVideoUserMicroStatus(name, true);
            }
        }
    }

}

class UserVideoMeta
{
    public string userId { get; set; }
    public string roomId { get; set; }
    public TRTCVideoStreamType streamType { get; set; }
    public int width { get; set; }
    public int height { get; set; }
    public uint fps { get; set; }
    public bool pureAudio { get; set; }
    public bool mainStream { get; set; }

    public UserVideoMeta()
    {
        userId = "";
        roomId = "";
        streamType = TRTCVideoStreamType.TRTCVideoStreamTypeBig;
        width = 0;
        height = 0;
        fps = 0;
        pureAudio = false;
        mainStream = false;
    }
}

[DataContract]
class HostMeetingResponse
{
    [DataMember(Name = "time")]
    public int Time { get; set; }

    [DataMember(Name = "count")]
    public int Count { get; set; }

    [DataMember(Name = "status")]
    public string Status { get; set; }

    [DataMember(Name = "hostid")]
    public string HostId { get; set; }

    [DataMember(Name = "msg")]
    public string Msg { get; set; }
}